Search code examples
javaexceptionmockingmockito

Mockito - 0 Matchers Expected, 1 Recorded (InvalidUseOfMatchersException)


I'm trying to mock up some mongo classes so that I don't need a connection (fairly standard stuff) but the following code gives me problems:

when(dbCollection.find(isA(DBObject.class))).thenReturn(dbCursor);

Running this get's me:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
at ...GridFileManagerTest.beforeClass(GridFileManagerTest.java:67)

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"));

For more info see javadoc for Matchers class.

If I were to do this though:

when(dbCollection.find(mock(DBObject.class))).thenReturn(dbCursor);

it no longer has that problem. This doesn't seem to accomplish what I want though - I want to return the value when the method is called with an object of type DBObject.

Thoughts?


Solution

  • I think your results are compatible with the result that would happen if dbCollection is not a Mockito-mock (or your method is static or final). That would mean that a matcher is being used where none can be used; hence the "0 matchers expected, 1 recorded".