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