java - 如何在 Mockito 中获取 session.getAttribute()
问题描述
这是我调用登录 servlet 以获取会话并在测试用例之间共享会话的模拟代码
public class MokitoExtension implements BeforeAllCallback, AfterAllCallback {
protected HttpSession httpSession;
public HttpSession getHttpSession() {
return httpSession;
}
@Override
public void beforeAll(ExtensionContext extensionContext) throws Exception {
Map<String, Object> attributes = new HashMap<>();
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
ServletOutputStream servletOutputStream = mock(ServletOutputStream.class);
httpSession = mock(HttpSession.class);
JSONObject reqObj = new JSONObject();
reqObj.put("AccessorCode", "userName");
reqObj.put("password" , "password");
when(request.getReader()).thenReturn(new BufferedReader(new StringReader(reqObj.toString())));
when(request.getHeader("Content-Type")).thenReturn("application/json");
when(response.getOutputStream()) .thenReturn(servletOutputStream);
when(request.getSession()) .thenReturn(httpSession);
// this line call login servlet and set session.setAttribute("accessor", authenticateAccessor);
new LogInAPI().doPost(request, response);
}
现在,当我想获取 httpSession.getAttribute("accessor") 但返回 null 时,如下所示,我的访问器存在, 我的 httpSession 响应图像在这里
然后尝试以这种方式获取会话
Mockito.doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock aInvocation) throws Throwable {
String key = (String) aInvocation.getArguments()[0];
Object value = aInvocation.getArguments()[1];
attributes.put(key, value);
return null;
}
}).when(httpSession).setAttribute(anyString(), anyObject())
但是此方法不适用于将会话属性放入 hashMap
我看到一些像这样的帖子点击这里,partial-mocking-on-httpsession,unable-to-put-spy-on-httpsession-mockito但不能解决我的问题
解决方案
推荐阅读
- php - Visual Studio 标记关闭自动完成功能不起作用
- swift - 为什么 Numeric 在 Swift 中使用负值?
- c++ - 如何在 QGraphicsView 中为右键单击创建上下文菜单
- elasticsearch - 使用json文件和curl命令将数据导入elasticsearch索引
- javascript - 在浏览器中执行 javascript(nodejs)
- android - WSL2 nativescript-vue 无法应用更改 ECONNREFUSED livesync
- css - 如何在 Angular 的 NgStyle 中应用默认值?
- flutter - 避免在颤振中在 navigator.push 上重新构建小部件
- python-3.x - 通过 For 循环检查列表中值的先前值和当前值
- jquery - VueJS - 未定义 Jquery