I got an InvalidUseOfMatchersException when using any () from Matchers with Mockito in JUnit. I will summarize the solution.
I wrote a test code like this.
@Test
public void testDoSomething() {
Hoge hoge = mock(Hoge.class)
when(hoge.doSomething(any(), "bar")).thenReturn(true);
}
Since the first argument of hoge.doSomething ()
was a class defined by ourselves, we put ʻorg.mockito.Matchers.any ()`.
The second argument is a String type and contains a specific character string.
When I ran the test in this state, I got the following Exception.
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
5 matchers expected, 3 recorded:
-> at hogehoge
-> at hogehoge
-> at hogehoge
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.
When using matchers, all arguments have to be provided by matchers.
As far as I read this error message, it seems that all the arguments need to be in matchers format. For String type arguments, it seems good to use ʻeq () `.
when(hoge.doSomething(any(), "bar")).thenReturn(true);
I changed the above code as follows and the Exception no longer occurs.
when(hoge.doSomething(any(), eq("bar"))).thenReturn(true);
I was saved by a polite error message that details the solution. Matchers is good.
Recommended Posts