gpt4 book ai didi

java - 如何使用 Mockito 模拟方法调用

转载 作者:行者123 更新时间:2023-11-29 04:36:48 24 4
gpt4 key购买 nike

我在使用 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 类的 write 和 close 方法被调用的测试结束。

我尝试了两种方法,但都没有成功:

@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 方法没有被调用,但我想测试的 handle 方法也没有被调用,所以测试失败了:

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);

有什么地方可能出错的线索吗?

最佳答案

在你的测试中而不是

RequestHandler requestHandler=mock(RequestHandler.class,CALLS_REAL_METHODS);

使用Mockito.spy():

      RequestHandler requestHandler=spy(RequestHandler.class);
doReturn(result).when(requestHandler).processRequest(httpRequest);

您可能需要 doReturn().when() 形式而不是 when().thenReturn() 因为第一个 不是 执行方法,而后者执行。


另一方面,我更愿意将 processRequest() 移动到另一个类,您可以在其中将一个实例注入(inject)到 RequestHandler 中,这将使模拟更直接。 .

关于java - 如何使用 Mockito 模拟方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41079004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com