Roee Gavirel Roee Gavirel - 6 months ago 98
Java Question

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

The class that I test receive a client wrapper:

The tested class (snippest)

private ClientWrapper cw
public Tested(ClientWrapper cw) {
this.cw = cw;
}

public String get(Request request) {
return cw.getClient().get(request);
}


The test initialization:

ClientWrapper cw = Mockito.mock(ClientWrapper.class);
Client client = Mockito.mock(Client.class);
Mockito.when(cw.getClient()).thenReturn(client);
//Here is where I want to alternate the return value:
Mockito.when(client.get(Mockito.any(Request.class))).thenReturn("100");


In the exmaple I always return "100", but the Request have an attribute
id
and I would like to return different values to
client.get(Request)
based on the
request.getId()
value.

How can I do it?

Answer

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;
   }
});
Comments