How to return different value in Mockito based on parameter attribute?

In order to do it right and with minimal code you have to use the ArgumentMatcher, lambda expression & don't forget to do a null check on the filters members in the ArgumentMatcher lambda (especially if you have more than one mock with the same ArgumentMatcher).

Customized argument matcher:

private ArgumentMatcher<Request> matchRequestId(final String target) {
    return request -> request != null &&
            target.equals(request.getId());
}

Usage:

 given(client.get(argThat(matchRequestId("1")))).willReturn("100");
 given(client.get(argThat(matchRequestId("2")))).willReturn("200");

You can use Mockito's answers, so instead of:

Mockito.when(client.get(Mockito.any(Request.class))).thenReturn("100");

write:

Mockito.when(client.get(Mockito.any(Request.class)))
 .thenAnswer(new Answer() {
   Object answer(InvocationOnMock invocation) {
     Object[] args = invocation.getArguments();
     Object mock = invocation.getMock();
     return "called with arguments: " + args;
   }
});

Tags:

Java

Mockito