本文介绍了模拟ActionContext.getContext().getSession()返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为以下方法编写jUnit测试用例.
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;
}
}
我遵循了此问题以及此问题,并尝试模拟ActionContext
.但是会话仍然是null
.
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 ?
推荐答案
将以下代码添加到上下文映射中,因为它是空上下文,因此您应将会话设置为操作上下文.
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));
这篇关于模拟ActionContext.getContext().getSession()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!