Explain Codes LogoExplain Codes Logo

Mockito: InvalidUseOfMatchersException

java
mockito
unittesting
best-practices
Alex KataevbyAlex Kataev·Dec 2, 2024
TLDR

Fixing InvalidUseOfMatchersException in Mockito involves consistent use of matchers for every argument in mocked method calls. The exception arises when mixing matchers (any(), eq(), etc.) with raw values.

when(mockObject.mockedMethod(anyInt(), anyString())).thenReturn("expectedResult");

To avoid the exception, apply the same matcher type to all arguments. For specific values, use the eq() matcher:

when(mockObject.mockedMethod(eq(42), eq("example"))).thenReturn("expectedResult");

Combining any() with eq() demands all arguments to stick with matchers:

when(mockObject.mockedMethod(anyInt(), eq("specificString"))).thenReturn("expectedResult");

Unlocking the matchers: Mockito's method requirements

To create rituals (mocks) in the sacred lands of Mockito, methods must be non-final and visible. Private shrines (private methods) or the divine decree (final methods) are out of reach. Change access levels to protected, if needed.

Void method mocking: doNothing().when()

Void methods, the silent type, require different syntax:

doNothing().when(mockObject).voidMethod(anyInt(), anyString());

Remember to keep the sequence of arguments consistent, or face the wrath of an InvalidUseOfMatchersException.

Diving into matcher intricacies

Working with spies

Spies require more caution. With doReturn(), you keep things consistent:

doReturn("expectedResult").when(spyObject).methodWithArgs(any(), any());

Selective method mocking

Invoke actual methods for unstubbed calls:

when(mockObject.someMethod(any())).thenCallRealMethod();

Keep an eye out for overloaded methods. Specify argument types when needed:

when(mockObject.someMethod(any(String.class), anyInt())).thenReturn("response");

Matcher documentation: Your compass

The Mockito ArgumentMatchers documentation is your guide. Consult it for best practices and matcher functions.

Avoiding common matcher traps

Misusing any()

any() can be misleading. Use any(Class<T>) for class-specific matchers:

when(mockObject.someMethod(any(MyClass.class))).thenReturn("response");

Trying to mock the unmockable

Private parties are intimate affairs, Mockito can't crash them! Static, private, or final methods are off-limits. Use overridable wrappers as your cloaking device.

Checking method calls

Verifying method calls? Keep all matchers, including eq(), on board:

verify(mockObject).someMethod(eq("specificString"), anyInt()); // No matcher left behind!