首页 > 解决方案 > 如何在 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-httpsessionunable-to-put-spy-on-httpsession-mockito但不能解决我的问题

标签: javatestingservletsmockitotdd

解决方案


推荐阅读