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?
Mockito Argument Matcher - eq() When we use argument matchers, then all the arguments should use matchers. If we want to use a specific value for an argument, then we can use eq() method.
Mockito mock() method All five methods perform the same function of mocking the objects. Following are the mock() methods with different parameters: mock() method with Class: It is used to create mock objects of a concrete class or an interface. It takes a class or an interface name as a parameter.
Following are the differences between thenReturn and doReturn : * Type safety : doReturn takes Object parameter, unlike thenReturn . Hence there is no type check in doReturn at compile time. In the case of thenReturn , whenever the type mismatches during runtime, the WrongTypeOfReturnValue exception is raised.
The thenReturn() methods lets you define the return value when a particular method of the mocked object is been called.
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; } });
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With