如何使用Mockito Java使用applicationType Json模拟http POST

Vit*_*lyT 1 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");
Run Code Online (Sandbox Code Playgroud)

我的问题是http POST请求正文.我希望它包含application/json类型内容.

像这样的东西,但是应答paras应该回答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);
        }
    });
Run Code Online (Sandbox Code Playgroud)

或者"公共对象回答..."可能不是用于Json返回的正确方法.

usersServlet.service(request, response);
Run Code Online (Sandbox Code Playgroud)

Yar*_*hiy 5

通过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");
Run Code Online (Sandbox Code Playgroud)

您可以使用DelegatingServletInputStreamSpring Framework中的类或只复制其源代码.