patternjavaCritical
Using Mockito with multiple calls to the same method with the same arguments
Viewed 0 times
withcallsmockitosametheusingmethodmultiplearguments
Problem
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
The code I'm looking to test looks something like this.
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 completionService =
new ExecutorCompletionService(service);
// Add all these tasks to the completion service
for (Callable 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 (...) { }
}Solution
You can do that using the
Or using the equivalent, static
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();Code Snippets
when(someMock.someMethod()).thenAnswer(new Answer() {
private int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count++ == 1)
return 1;
return 2;
}
});doAnswer(new Answer() {
private int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count++ == 1)
return 1;
return 2;
}
}).when(someMock).someMethod();Context
Stack Overflow Q#8088179, score: 356
Revisions (0)
No revisions yet.