Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 563
VitalyT Avatar asked Sep 23 '26 12:09

VitalyT


1 Answers

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.

like image 136
Yaroslav Stavnichiy Avatar answered Sep 26 '26 01:09

Yaroslav Stavnichiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!