dimanche 1 novembre 2020

get session value in Mockito

this is my mockito code to call login servlet to get session and share the session between test case

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);

    }

Now When I Want to get request.getSession("accessor") but return null

then Try to get Session with this way

 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())

but this method don't work for put session attribute into hashMap

I see some posts like this click here, partial-mocking-on-httpsession but not solve my issue

Aucun commentaire:

Enregistrer un commentaire