我正在创建一个测试HTTP相互作用的通用模拟客户端。为此,我希望能够用同样的方法做出许多回应。 与正常的模拟,这将不会是一个问题:嘲笑部分模拟与Mockito连续响应的通用数
when(mock.execute(any(), any(), any())).thenReturn(firstResponse, otherResponses)
不过,我使用的是部分模拟,在这里我只是想嘲笑方法使HTTP请求,因为可能没有进入到现场在单元测试执行的上下文中,对于这个问题,通常是终点或因特网。
所以我会做这样的事情:
doReturn(response).when(spy).execute(hostCaptor.capture(), requestCaptor.capture(), contextCaptor.capture());
不过,我想能够支持多个响应(没有太多的“互动”的)。但是没有任何一种方法,一次只能得到一个以上的答案。
我一个解决方案的首次尝试是反复地做到这一点:
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());
这并不能然而,以验证运行测试时(“未完成的磕碰检测”)。
所以 - 有没有办法用Mockito实现这一点?
感谢您的阅读。
谢谢您回答大卫,但我的问题是,我通常不知道r的数量响应,因为它是一个数组(或可变参数)。 – tveon 2012-03-29 07:56:27
@tveon好的,看我的编辑如何处理这种情况。 – 2012-03-29 08:29:37
这看起来正是我在找的东西。 :) – tveon 2012-03-29 13:29:33