java - 如何使用 Mockito Java 模拟带有 applicationType Json 的 http POST

标签 java servlets mocking mockito

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

最佳答案

通过 request.getInputStream() 或通过 request.getReader() 方法访问 Post 请求正文。这些是您需要模拟以提供 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 .

关于java - 如何使用 Mockito Java 模拟带有 applicationType Json 的 http POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41542703/

相关文章:

java - Mockito 可以验证参数是否具有某些属性/字段?

c# - HttpContextWrapper 就那么……有用吗?

java - java中如何从1而不是0初始化位置

java - 请推荐一些学习切入点表达式的教程

spring - 如何在容器级别使遗留 webapp spring 感知 bean Autowiring 到 Servlet 中?

java - 请求参数在 Tomcat 中被丢弃

java - 为什么我们必须在 web.xml 文件中指定 <web-app> 标签的属性?

c# - 你如何为单元测试最小化一个类

java - Titanium Mobile 是否将 Javascript 转换为 native Java 或 Objective C 编译代码?

java - 如何在 Java 中压缩字符串?