Tasty Test Tip: Matching generic typed classes in Mockito

Say you have a arbitrary class under test, which is dependent on a class DataProcessor which has a method with the following signature:

 String processData((String data, MultivaluedMap  params, Token token)

you might want to stub it with Mockito 1.9.5 in the following way to match the generic typed class:

when(dataProcessor.processData(anyString(), any(MultivaluedMap.class), any(Token.class))).thenReturn(processedData);

However running this, gives the following error:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
3 matchers expected, 4 recorded:
[ ....]
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));

This is caused by the generic typed MulitvaluedMap.

Solution:

 MultivaluedMap  map = Mockito.any();
when(dataHandlerMock.getResult(anyString(), map, any(TokenDataBean.class))).thenReturn(jsonString);

Run the test and it will pass (these lines at least :-)!

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *