如何使用Mockito Java模拟带有applicationType Json的http POST请求

3

我希望模拟使用json数据的http POST请求。

对于GET方法,我用以下代码成功了:

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("xxx@aaa-app.com");

我的问题是关于http POST请求体。我希望它包含application/json类型的内容。

类似这样,但是应该使用什么请求参数来响应json呢?

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

或者说,"public Object answer..." 可能不是用于返回 Json 数据的正确方法。

usersServlet.service(request, response);
1个回答

8

POST请求的请求体可以通过request.getInputStream()或者request.getReader()方法来获取。要提供JSON内容,您需要模拟这些方法。确保还模拟了getContentType()方法。

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

你可以使用Spring Framework中的DelegatingServletInputStream类,或者只需复制它的源代码


请问,您能否提供一个关于我的具体问题的示例/解决方案? :) - VitalyT
编译错误:--> when(request.getInputStream()).thenReturn(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))); -- 将inputstream转换为ByteArrayInputStream。 - VitalyT
谢谢,它有效 :). 如果您能看到另一个问题,可能对您来说会更容易 :) http://stackoverflow.com/questions/41541827/how-export-app-engine-datastore-data-to-localhost-using-gradle-task - VitalyT
你说的“request”是什么意思?在单元测试中如何创建那个对象? - alexcornejo
@JACA 请查看原始问题:request = mock(HttpServletRequest.class) - Yaroslav Stavnichiy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接