VitalyT
VitalyT

Reputation: 1691

How to mock http POST with applicationType Json with Mockito Java

I want to mock http POST with json data.

For GET method I succedded with the following code:

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

when(request.getMethod()).thenReturn("GET");
when(request.getPathInfo()).thenReturn("/getUserApps");
when(request.getParameter("userGAID")).thenReturn("test");
when(request.getHeader("userId")).thenReturn("[email protected]");

My problem is with http POST request body. I want it to contain application/json type content.

Something like this, but what should be the request params to answer json response?

HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);

when(request.getMethod()).thenReturn("POST");
when(request.getPathInfo()).thenReturn("/insertPaymentRequest");
when( ????  ).then( ???? maybe ?? // new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        new Gson().toJson("{id:213213213 , amount:222}", PaymentRequest.class);
        }
    });

Or maybe "public Object answer..." is not the correct method to use for Json return.

usersServlet.service(request, response);

Upvotes: 3

Views: 12389

Answers (1)

Yaroslav Stavnichiy
Yaroslav Stavnichiy

Reputation: 21446

Post request body is accessed either via request.getInputStream() or via request.getReader() method. These are what you need to mock in order to provide your JSON content. Make sure to mock getContentType() as well.

String json = "{\"id\":213213213, \"amount\":222}";
when(request.getInputStream()).thenReturn(
    new DelegatingServletInputStream(
        new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))));
when(request.getReader()).thenReturn(
    new BufferedReader(new StringReader(json)));
when(request.getContentType()).thenReturn("application/json");
when(request.getCharacterEncoding()).thenReturn("UTF-8");

You can use DelegatingServletInputStream class from Spring Framework or just copy its source code.

Upvotes: 8

Related Questions