Mocking total consecutive responses from partial mock with Mockito

I am creating a generic generic client mock for testing HTTP interactions. For this, I would like to make multiple answers of the same method. This won't be a problem with a regular mocker:

when(mock.execute(any(), any(), any())).thenReturn(firstResponse, otherResponses)

      

However, I am using a partial mock where I just want to mock the method making the HTTP request, as it may not be possible to access the real time endpoint or the internet in general in the context where the -tests unit is being executed.

So, I'll 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 answer (not much "interaction"). But there is no doReturn method that accepts more than one response at a time.

My first attempt at 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());

      

However, validation does not perform validation ("Incomplete discovery detected").

So - is there a way to achieve this with Mockito?

Thanks for reading.

+3


source to share


2 answers


You can write

doReturn( 1 ).doReturn( 2 ).doReturn( 3 ).when( myMock ).myMethod( any(), any(), any());

      

Edit:



If the values ​​you want are in an array myArray

, you can also use

import static java.util.Arrays.asList;
import static org.mockito.Mockito.doAnswer;
import org.mockito.stubbing.answers.ReturnElementsOf

....

doAnswer( new ReturnsElementsOf( asList( myArray )))
   .when( myMock ).myMethod( any(), any(), any());

      

+3


source


The solution I found was to use doAnswer

to return the next answer in an array.



Answer<HttpResponse> answer = new Answer<HttpResponse>() {

    HttpResponse[] answers = responses;
    int number = 0;

    @Override
    public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
        HttpResponse result = null;
        if (number <= answers.length) {
            result = answers[number]; 
            number++;
        } else {
            throw new IllegalStateException("No more answers");
        }
        return result;
    }
};
doAnswer(answer).when(spy).execute(hostCaptor.capture(), requestCaptor.capture(), contextCaptor.capture());

      

+1


source







All Articles