首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟ActionContext.getContext().getSession()返回null

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

Stack Overflow用户
提问于 2017-07-06 02:56:07
回答 1查看 943关注 0票数 2

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

代码语言:javascript
复制
public class MyClass {

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

我关注了this question和this question,并试图模仿ActionContext。但session仍然是null

代码语言:javascript
复制
    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

    }

}

我是不是做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-06 04:32:02

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

代码语言:javascript
复制
contextMap.put(ActionContext.SESSION, new SessionMap(request));
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44933997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档