【发布时间】:2017-07-05 18:56:06
【问题描述】:
我正在尝试为以下方法编写 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
}
}
我在这里做错了吗?
【问题讨论】:
-
您从哪里获得
null会话?在testGetSession()或getSession() -
@alayor on testGetSession()
-
我猜你需要显示来自
MyClass的代码。你能显示这个类从ActionContext返回会话的代码吗? -
@alayor 我编辑了我原来的问题
标签: java junit struts2 mockito actioncontext