Search code examples
javajunitstruts2mockitoactioncontext

Mocking ActionContext.getContext().getSession() returns null


I am trying to write jUnit test case for following method.

public class MyClass {

  public static Map<String, Object> getSession() {
    Map<String, Object> session = ActionContext.getContext().getSession();
    return session;
  }
}

I followed this question and also this question and tried to mock ActionContext. But still session is null.

    public class TestClass {
        
        private HttpServletRequest request;
        private HttpSession session;
    
        @Before
        public void setUp() {
            // mock the session
            session = mock(HttpSession.class);
            // mock the request
            request = mock(HttpServletRequest);
            when(request.getSession()).thenReturn(session);
    
            // set the context
            Map<String, Object> contextMap = new HashMap<String, Object>();
            contextMap.put(StrutsStatics.HTTP_REQUEST, request);
            ActionContext.setContext(new ActionContext(contextMap));
        }
    
        @After
        public void destroyTests() {
           ActionContext.setContext(null);
        }

@Test
    public void testGetSession() {        
        Map<String, Object> session =MyClass.getSession();
        //session is null here

    }

}

Is there something I am doing wrong here ?


Solution

  • Add the following code to the context map, since it's empty context created you should set the session into action context.

    contextMap.put(ActionContext.SESSION, new SessionMap(request));