[Solved] org.mockito.exceptions.misusing.InvalidUseOfMatchersException

InvalidUseOfMatchersException is RuntimeException and subclass of MockitoException. It throws when trying to push behavior on object which is not mock.


  • InvalidUseOfMatchersException() : Will throw exception.
  • InvalidUseOfMatchersException(String message) : Will throw exception with message.


Here in below example mock Map interface and creating stub for get method to return fixed String for any type of String elements.

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;

public class MockitoApplicationTester {

public void second_stubbing_throws_InCorrectUseOfAPI() throws Exception {
// Mock of Map interface
Map<String, String> mapMock = mock(Map.class);
Map<String, String> mapReal = new HashMap<String, String>();

//Issue is here because performing argument matcher without mock object
when(mapReal.get(anyString())).thenReturn("1st stubbing");

//Correct statement
when(mapMock.get(anyString())).thenReturn("1st stubbing");

Assert.assertEquals(mapMock.get("Test"), "1st stubbing");




Misplaced argument matcher detected here:

-> at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_InCorrectUseOfAPI(MockitoApplicationTester.java:22)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_InCorrectUseOfAPI(MockitoApplicationTester.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)


Here in above code is throwing this exception because using real object to create stub that’s what throwing “InvalidUseOfArgumentMatchersException“. To fix above this comment out wrong statement and execute again.

This exception can occurred by others ways also:

  1. This error might show up because you use argument matchers with methods that cannot be mocked.
  2. Stubbed and verified method can be used on final/private/equals()/hashCode() methods.
  3. Mocking methods declared on non-public parent classes is not supported.



Know More

To know more about Junit, Mockito and exception solutions follow below links: