如何使用Mockito Java

时间:2017-01-09 07:08:57

标签: 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类型的内容。

这样的事情,但是请求params应该回答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);

1 个答案:

答案 0 :(得分: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");

您可以使用Spring Framework中的DelegatingServletInputStream类,或只复制其source code