question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Non-sensical "Invalid use of argument matchers!" error

See original GitHub issue

I am using org.mockito:mockito-core:1.9.0 with junit:junit:4.11. I have the following code which I need to test:

public class ClassUnderTest {
    public void methodToTest(DependencyToBeMocked dependencyToBeMocked, Helper helper) {
        Long id = dependencyToBeMocked.doSomething("", "");
        try {
            helper.doSomething();
        } catch (IllegalArgumentException ex) {
            throw new IllegalStateException("test message", ex);
        }
    }
}

public interface DependencyToBeMocked {
    Long doSomething(String param1, String param2);
}

public class Helper {
    public void doSomething() {
    }
}

I write a test for this as:

import org.junit.*;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import static org.mockito.MockitoAnnotations.*;
import static org.mockito.Mockito.*;

public class MyTest {
    @Mock DependencyToBeMocked dependencyToBeMocked;
    @Mock Helper helper;
    @Rule public ExpectedException expectedException = ExpectedException.none();

    @Before
    public void setUp() {
        initMocks(this);
        when(dependencyToBeMocked.doSomething(anyString(), anyString())).thenReturn(4L);
    }

    @Test
    public void myTest() {
        doThrow(new IllegalArgumentException()).when(helper).doSomething();
        expectedException.expect(IllegalStateException.class);
        // This is incorrect usage of the API; but still causes Mockito
        // to throw an incomprehensible error message
        expectedException.expectMessage(contains("test message"));

        ClassUnderTest fixture = new ClassUnderTest();
        fixture.methodToTest(dependencyToBeMocked, helper);
    }
}

In this test I accidentally used Matchers.contains() incorrectly. But the error message I got was not at all helpful:

java.lang.AssertionError: 
Expected: (an instance of java.lang.IllegalStateException and exception with message a string containing "")
     but: an instance of java.lang.IllegalStateException <org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded.
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.> is a org.mockito.exceptions.misusing.InvalidUseOfMatchersException
Stacktrace was: org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded.
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.
    at ClassUnderTest.methodToTest(ClassUnderTest.java:5)
    at MyTest.myTest(MyTest.java:29)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:168)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)

I wasted much time chasing this down, so filing this here. Interestingly, if I remove the second String parameter from DependencyToBeMocked, I don’t hit this exception! The test passes - but because Matchers.contains() returns an empty string and that is a substring of all non-null strings. But I am curious what this seemingly innocuous change can have.

public interface DependencyToBeMocked {
    Long doSomething(String param1 /*, String param2*/);
}

public class ClassUnderTest {
    public void methodToTest(DependencyToBeMocked dependencyToBeMocked, Helper helper) {
        Long id = dependencyToBeMocked.doSomething(""/*, ""*/);         
        // .. same as before
    }
}

public class MyTest {
    @Before
    public void setUp() {
        initMocks(this);
        when(dependencyToBeMocked.doSomething(anyString()/*, anyString()*/)).thenReturn(4L);
    }   
    // .. same as before
}

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:9 (3 by maintainers)

github_iconTop GitHub Comments

3reactions
rafaelromaocommented, Aug 28, 2020

I was having this error message when doing thenReturn(any(Something.class)) and solved by doing thenReturn(mock(Something.class)). The weirdest thing is that the original code works when debugging line by line. Maybe an error message that is more clear would help.

0reactions
hannah23280commented, Mar 29, 2022

Hey guys, just for record and help anyone whose is going through it and avoiding him/her to waste their time like me xD. NOTE: I don’t know Mockito so well, so I could be telling you something a little bit wrong, Please correct me if I am wrong about it.

If you going through this and doesn’t get the logic of this error, the comment of @bric3 is very enlightened about what happened there. The thing is that when you run a test, all static methods must be evaluated before the rest actually runs, and as Mockito has a cache system for matchers instances, if you put some matchers when you run your test you will subscribe the early matchers set already created.

Example (my context problem here):

when I do

 doAnswer(invocationOnMock -> new Exception("Any Error")).when(service)
                .productCatalog(anyString(), anyString(), anyString(), anyString(), anyString(), anyLong(),
                anyString(), anyString(), anyInt(), anyString(), anyInt(), anyString(), anyInt());

I’m telling to mockit to create 13 matchers instances that 9 are strings, 3 are integers and 1 long type.

after this, I tried to run my test by writing this:

  ApiException returnedException = assertThrows(
          ApiException.class,
          () -> controller.productCatalog(anyString(),anyString(), anyString(),
                  anyString(), anyLong(), anyString(), anyString(), anyInt(),
                  anyString(), anyInt(), anyString(), anyInt())
  );

then I got the Invalid InvalidUseOfMatchersException telling me that there’s a mock method waiting for 13 matchers but only exists 12 recorded. This happen because the secode set of matchers override the first one.

The correct way to test my function is by writing this:

  ApiException returnedException = assertThrows(
                  ApiException.class,
                  () -> controller.productCatalog("", "", "", "", 1L,
                          "", "", 1, "", 1, "", 1)
          );

regards ❤️

Hi, I am quite confuse, If the productCatalog is expecting 13 arguments, why are you still able to pass in 12 arguments of raw value without getting compilation error?

Read more comments on GitHub >

github_iconTop Results From Across the Web

Invalid use of argument matchers - java - Stack Overflow
1 Answer 1 · 2. add import static org. · 1. above change gives compile time error as "The method eq(Class<String>) is undefined...
Read more >
Best of Java : ERROR - org.mockito.exceptions.misusing ...
Invalid use of argument matchers! This exception may occur if matchers are combined with raw values: //incorrect: someMethod(anyObject(), "raw String");
Read more >
Mockito - Invalid Use Of Argument Matchers - ADocLib
It somehow does work, though it generates the nonsensical raw type warning. InvalidUseOfMatchersException: Invalid use of argument matchers!
Read more >
Mockito 3 - Invalid use of Argument Matchers - YouTube
Personal queries? - Follow me on LinkedIn - https://www.linkedin.com/in/dinesh-varyani/ ▻ ▻This video is part of my Complete Mastering ...
Read more >
Bug descriptions — spotbugs 4.7.3 documentation
To correctly override the compareTo() method in the Comparable interface, the parameter of compareTo() must have type java.lang.Object . IC: Superclass uses ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found