2
我想用json數據模擬http POST。如何使用Mockito Java模擬帶有applicationType Json的HTTP POST
對於GET方法我succedded用下面的代碼:
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("[email protected]");
我的問題是與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 return的正確方法。
usersServlet.service(request, response);
請問,你能提供一個例子/解決方案,我的具體問題:) – VitalyT
@VitalyT我已經更新了我的答案示例代碼 –
得到編譯錯誤: - > when(request.getInputStream())。thenReturn(new ByteArrayInputStream進行(json.getBytes(StandardCharsets.UTF_8))); --inputstream ByteArrayInputStream – VitalyT