【问题标题】:How to mock http POST with applicationType Json with Mockito Java如何使用 Mockito Java 使用 applicationType Json 模拟 http POST
【发布时间】:2017-05-23 09:36:33
【问题描述】:

我想用 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);
        }
    });

或者也许“公共对象答案...”不是用于 Json 返回的正确方法。

usersServlet.service(request, response);

【问题讨论】:

    标签: java servlets mocking mockito


    【解决方案1】:

    通过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 类,或者直接复制其 source code

    【讨论】:

    • 拜托,你能为我的具体问题提供一个例子/解决方案吗:)
    • 得到编译错误:--> when(request.getInputStream()).thenReturn(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8))); --inputstream 到 ByteArrayInputStream
    • 谢谢,它有效:)。也许如果你能看到另一个问题,也许对你来说很容易:) stackoverflow.com/questions/41541827/…
    • “请求”是什么意思?如何在单元测试中创建该对象?
    • @JACA 查看原始问题:request = mock(HttpServletRequest.class)
    猜你喜欢
    • 2018-02-27
    • 2021-04-30
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 2016-05-08
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多