Mockito: InvalidUseOfMatchersException
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.
To avoid the exception, apply the same matcher type to all arguments. For specific values, use the eq() matcher:
Combining any() with eq() demands all arguments to stick with matchers:
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:
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:
Selective method mocking
Invoke actual methods for unstubbed calls:
Keep an eye out for overloaded methods. Specify argument types when needed:
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:
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:
Was this article helpful?