Search code examples
juniteasymockhttpsession

EasyMock - HttpSession Setting session - method pass via request


I'm wondering on a request pass to a method and pulling the HttpSession?

Following from JUnit:

@Test
public void testSessionPass(){
    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpSession session = createMock(HttpSession.class);
    expect(session.getAttribute("testAttribute")).andReturn("testValue").anyTimes();
    replay(request);
    replay(session);

    CAction cAction = new CAction();
    cAction.test(request);


}

In the CAction:

 public void test (HttpServletRequest request){
        HttpSession session = request.getSession();
        if(session.getAttribute("testAttribute")!=null){
             System.out.println((String)session.getAttribute("testAttribute"));
        }
 }

UPDATE:

Why am I loosing the session from the passed request value at line HttpSession session = request.getSession(); ??


Solution

  • You aren't mocking the call to getSession()

    Add this line before your calls to replay()

    expect(request.getSession()).andReturn(session);