gpt4 book ai didi

mockito - 使用 Mockito 模拟来自部分模拟的连续响应的通用数量

转载 作者:行者123 更新时间:2023-12-01 12:55:44 30 4
gpt4 key购买 nike

我正在创建一个通用模拟客户端来测试 HTTP 交互。为此,我希望能够以相同的方法进行多次响应。使用普通模拟,这不是问题:

when(mock.execute(any(), any(), any())).thenReturn(firstResponse, otherResponses)

但是,我使用的是部分模拟,我只是想模拟发出 HTTP 请求的方法,因为在单元所在的上下文中可能无法访问实时端点或一般互联网-执行测试。

所以我会做类似的事情:

doReturn(response).when(spy).execute(hostCaptor.capture(), requestCaptor.capture(), contextCaptor.capture());

但是,我希望能够支持多个响应(不是很多“交互”)。但是没有 doReturn 方法,它一次需要多个响应。

我对解决方案的第一次尝试是迭代地进行:

Stubber stubber = null;
for (HttpResponse response : responses) {
if (stubber == null) {
stubber = doReturn(response);
} else {
stubber = stubber.doReturn(response);
}
}
stubber.when(spy).execute(hostCaptor.capture(), requestCaptor.capture(), contextCaptor.capture());

然而,这在运行测试时无法验证(“检测到未完成的 stub ”)。

那么 - 有没有办法用 Mockito 实现这个目标?

感谢阅读。

最佳答案

你可以写

doReturn( 1 ).doReturn( 2 ).doReturn( 3 ).when( myMock ).myMethod( any(), any(), any());

编辑:

如果你想要的值在数组myArray中,那么你也可以使用

import static java.util.Arrays.asList;
import static org.mockito.Mockito.doAnswer;
import org.mockito.stubbing.answers.ReturnElementsOf

....

doAnswer( new ReturnsElementsOf( asList( myArray )))
.when( myMock ).myMethod( any(), any(), any());

关于mockito - 使用 Mockito 模拟来自部分模拟的连续响应的通用数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9911397/

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