Question

I recently upgrade Maven Surefire plugin to version v2.14.1 (from v2.6) in my project. After this upgrade Mockito started throwing InvalidUseOfMatchersException in all JUnit tests where a Mockito.mock() method is invoked on an 'interface' or 'abstract class'. Same Unit Test works fine when executed through Eclipse, but always fails while building with Maven.

 Here are few examples of calls that are failing:

 i) DataSource dataSource = Mockito.mock(DataSource.class);

ii) DatabaseMetaData metaData = mock(DatabaseMetaData.class);

iii) ResultSet rs = mock(ResultSet.class);
Was it helpful?

Solution

InvalidUseOfMatchersException is almost never caused by a call to Mockito.mock(); rather, the call to Mockito.mock() tells Mockito to validate that it's not in the middle of something, which is when it determines that it should throw a InvalidUseOfMatchersException. Your error is probably related to Maven/Surefire because it's executing your test methods in a different order than Eclipse does, or because Maven is reusing a JVM where Eclipse isn't.

Mockito matchers are static functions that return dummy values (but that secretly log their calls with Mockito). Internally, Mockito keeps a stack of previously-called matchers, one per thread, so if you call a Matcher at the end of a test method it will linger around to pollute the next test method in the same thread.

The easiest way to pin this down is to put a call to Mockito.validateMockitoUsage() in your tearDown method (JUnit3) or an @After method (JUnit4). That will cause the test method that misuses Mockito to fail there, rather than in whatever next method that runs.

As for the actual Matcher misuse? Double-check that every time you use a Matcher from org.mockito.Mockito or org.mockito.Matchers, you're actually matching every single argument in the function; I went over the reasons in a separate SO answer. Be particularly wary of calling other mocks from within your calls to when or verify (which interferes with Mockito's static magic) or when trying to stub or verify any method marked final (which will fail silently because the VM calls the actual implementation instead).

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top