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

编程入门 行业动态 更新时间:2024-10-28 16:21:36
本文介绍了模拟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

本文发布于:2023-10-31 05:23:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545135.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:getContext   ActionContext   null   getSession

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!