I am creating a general general mock-client for testing HTTP-interactions. For this, I would like to be able to make a number of responses of the same method.
With a normal mock, this would not be a problem:
when(mock.execute(any(), any(), any())).thenReturn(firstResponse, otherResponses)
However, I am using a partial mock, where I simply want to mock method making the HTTP request, since there might not be access to a live end-point or the Internet in general for that matter in the context where the unit-tests are executed.
So I will be doing something like:
doReturn(response).when(spy).execute(hostCaptor.capture(), requestCaptor.capture(), contextCaptor.capture());
However, I would like to be able to support more than one response (not much of an “interaction”). But there are no doReturn-method, which takes a more than a single response at a time.
My first attempt on a solution was to do it iteratively:
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());
This does however fail to verify (“Unfinished stubbing detected”) when running the test.
So – is there a way to achieve this with Mockito?
Thanks for reading.
You can write
Edit:
If the values you want are in the array
myArray, then you could also use