Search code examples
javajunitmockingjmock

How is Jmock used with HttpSession and HttpServletRequest


I am new to jmock and trying to mock an HttpSession. I am getting:

java.lang.AssertionError: unexpected invocation: httpServletRequest.getSession() no expectations specified: did you... - forget to start an expectation with a cardinality clause? - call a mocked method to specify the parameter of an expectation?

the test method:

@Test

public void testDoAuthorization(){

    final HttpServletRequest request = context.mock(HttpServletRequest.class);
    final HttpSession session = request.getSession();

    context.checking(new Expectations(){{
       one(request).getSession(true); will(returnValue(session));
   }});

    assertTrue(dwnLoadCel.doAuthorization(session));
}

I have done a bit of searching and it isn't clear to me still how this is done. Feels like I am missing some small piece. Anyone with experience in this can just point me in the right direction. thanks


Solution

  • You don't need to mock the request object. Since the method you're testing (dwnLoadCel.doAuthorization()) only depends on an HttpSession object, that is what you should mock. So your code would look like this:

    public void testDoAuthorization(){
        final HttpSession session = context.mock(HttpSession.class);
    
        context.checking(new Expectations(){{
            // ???
        }});
    
        assertTrue(dwnLoadCel.doAuthorization(session));
    

    }

    The question becomes: what do you expect the SUT to actually do with the session object? You need to express in your expectations the calls to session and their corresponding return values that are supposed to result in doAuthorization returning true.