本文介绍了使用Mockito多次调用具有相同参数的相同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法让stubbed方法在后续调用中返回不同的对象?我想这样做来测试来自 ExecutorCompletionService
的非确定响应。即,无论方法的返回顺序如何测试,结果都保持不变。
Is there a way to have a stubbed method return different objects on subsequent invocations? I'd like to do this to test nondeterminate responses from an ExecutorCompletionService
. i.e. to test that irrespective of the return order of the methods, the outcome remains constant.
我想要测试的代码看起来像这样。
The code I'm looking to test looks something like this.
// Create an completion service so we can group these tasks together
ExecutorCompletionService<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 (...) { }
}
推荐答案
你可以使用方法(与时:
You can do that using the thenAnswer
method (when chaining with when
):
when(someMock.someMethod()).thenAnswer(new Answer() {
private int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count++ == 1)
return 1;
return 2;
}
});
或使用等效的静态方法:
Or using the equivalent, static doAnswer
method:
doAnswer(new Answer() {
private int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count++ == 1)
return 1;
return 2;
}
}).when(someMock).someMethod();
这篇关于使用Mockito多次调用具有相同参数的相同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!