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

左心房为你撑大大i 提交于 2019-12-22 18:11:57

问题


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 ?


回答1:


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));


来源:https://stackoverflow.com/questions/44933997/mocking-actioncontext-getcontext-getsession-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!