How to mock HTTPSession/FlexSession with TestNG and some Mocking Framework
        Posted  
        
            by 
                ifischer
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by ifischer
        
        
        
        Published on 2011-01-16T01:33:14Z
        Indexed on 
            2011/01/16
            10:53 UTC
        
        
        Read the original article
        Hit count: 705
        
I'm developing a web application running on Tomcat 6, with Flex as Frontend. I'm testing my backend with TestNG. Currently, I'm trying to test the following method in my Java-Backend:
public UserPE login(String mail, String password) {
    UserPE dbuser = findUserByMail(mail); 
    if (dbuser == null || !dbuser.getPassword().equals(password))
        throw new RuntimeException("Invalid username and/or password");
    // Save logged in user
    FlexSession session = FlexContext.getFlexSession();
    session.setAttribute("user", dbuser);
    return dbuser;
}
The method needs access to the FlexContext which only exists when i run it on the Servlet container (don't bother if you don't know Flex, it's more a Java-Mocking question in general). Otherwise i get a Nullpointer exception when calling session.setAttribute(). 
Unfortunately, I cannot set the FlexContext from outside, which would make me able to set it from my tests. It's just obtained inside the method.
What would be the best way to test this method with a Mocking framework, without changing the method or the class which includes the method? And which framework would be the easiest for this use case (there are hardly other things i have to mock in my app, it's pretty simple)?
Sorry I could try out all of them for myself and see how i could get this to work, but i hope that i'll get a quickstart with some good advices!
© Stack Overflow or respective owner