2017-01-09 51 views
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); 

回答

4

發佈請求體或者通過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"); 

您可以使用DelegatingServletInputStream類從Spring框架或只是複製其source code

+0

請問,你能提供一個例子/解決方案,我的具體問題:) – VitalyT

+0

@VitalyT我已經更新了我的答案示例代碼 –

+0

得到編譯錯誤: - > when(request.getInputStream())。thenReturn(new ByteArrayInputStream進行(json.getBytes(StandardCharsets.UTF_8))); --inputstream ByteArrayInputStream – VitalyT