使用Mockito与具有相同参数的多次调用相同方法
有没有一种方法可以使存根方法在后续调用中返回不同的对象?我想这样做是为了测试来自的不确定响应ExecutorCompletionService
。即,不管方法的返回顺序如何进行测试,结果都保持恒定。
我要测试的代码看起来像这样。
// Create an completion service so we can group these tasks togetherExecutorCompletionService<T> completionService =
new ExecutorCompletionService<T>(service);
// Add all these tasks to the completion service
for (Callable<T> t : ts)
completionService.submit(request);
// As an when each call finished, add it to the response set.
for (int i = 0; i < calls.size(); i ++) {
try {
T t = completionService.take().get();
// do some stuff that I want to test
} catch (...) { }
}
回答:
你可以使用thenAnswer
方法来做到这一点(与链接时when
):
when(someMock.someMethod()).thenAnswer(new Answer() { private int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count++ == 1)
return 1;
return 2;
}
});
或使用等效的静态doAnswer方法:
doAnswer(new Answer() { private int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count++ == 1)
return 1;
return 2;
}
}).when(someMock).someMethod();
以上是 使用Mockito与具有相同参数的多次调用相同方法 的全部内容, 来源链接: utcz.com/qa/432871.html