模拟ActionContext.getContext()。getSession()返回null

时间:2017-07-05 18:56:07

标签: junit struts2 mockito actioncontext

我正在尝试为以下方法编写jUnit测试用例。

public class MyClass {

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

我问了this个问题,还问了this个问题并试图模仿ActionContext。但仍然会话是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

    }

}

我在这里做错了吗?

1 个答案:

答案 0 :(得分:1)

将以下代码添加到上下文映射中,因为它创建了空上下文,您应该将会话设置为操作上下文。

contextMap.put(ActionContext.SESSION, new SessionMap(request));
相关问题