1
方法調用我有使用的Mockito單元測試以下問題:如何嘲笑使用的Mockito
我有這樣的方法:
@Override
public void handle(HttpExchange httpRequest) throws IOException {
Object[] outputResult = processRequest(httpRequest);
String response = (String) outputResult[0];
Integer responseCode = (Integer) outputResult[1];
httpRequest.sendResponseHeaders(responseCode, response.length());
OutputStream os = httpRequest.getResponseBody();
os.write(response.getBytes());
os.close();
}
我只想測試這種方法,而不是processRequestMethod
這是內部調用的(我想在anthoer測試中單獨測試),所以我需要嘲笑它並在測試結束時檢查方法寫和關閉OutputStream
類已被調用。
我已經嘗試了兩種方式,但沒有人沒有運氣:
@Test
public void handleTest() throws IOException {
RequestHandler requestHandler=mock(RequestHandler.class);
String response = "Bad request";
int responseCode = HttpURLConnection.HTTP_BAD_REQUEST;
Object[] result={response,responseCode};
when(requestHandler.processRequest(anyObject())).thenReturn(result);
when (httpExchange.getResponseBody()).thenReturn(outputStream);
requestHandler.handle(httpExchange);
Mockito.verify(outputStream,times(1)).write(anyByte());
Mockito.verify(outputStream,times(1)).close();
}
通過上面的代碼中,processRequest
方法不叫,但也不是說我想測試手柄的方法,所以測試失敗:
Mockito.verify(outputStream,times(1)).write(anyByte());
說這個方法根本沒有被調用。
但是如果我添加參數CALL_REAL_METHODS
創建模擬,像這樣的時候:
@Test
public void handleTest() throws IOException {
RequestHandler requestHandler=mock(RequestHandler.class,CALLS_REAL_METHODS);
String response = "Bad request";
int responseCode = HttpURLConnection.HTTP_BAD_REQUEST;
Object[] result={response,responseCode};
when(requestHandler.processRequest(anyObject())).thenReturn(result);
when (httpExchange.getResponseBody()).thenReturn(outputStream);
requestHandler.handle(httpExchange);
Mockito.verify(outputStream,times(1)).write(anyByte());
Mockito.verify(outputStream,times(1)).close();
}
然後processRequest
的方法,我想跳過實際上是調用方法時執行該行:
when(requestHandler.processRequest(anyObject())).thenReturn(result);
任何可能出錯的線索?
不知道間諜。它像一個魅力。謝謝! – fgonzalez