I got an InvalidUseOfMatchersException when using any with JUnit Mock

Introduction

I got an InvalidUseOfMatchersException when using any () from Matchers with Mockito in JUnit. I will summarize the solution.

Symptoms

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.

analysis

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 () `.

Solution

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);

at the end

I was saved by a polite error message that details the solution. Matchers is good.

Recommended Posts

I got an InvalidUseOfMatchersException when using any with JUnit Mock
When I bcrypt with node + docker, I got an error
I got an error when using nextInt, nextLine and substring.
When I ran a jar created using WildFly Swarm, I got an InvocationTargetException.
Test code using mock with JUnit (EasyMock center)
I got stuck when port forwarding with VBox
I got an error when I ran rake routes.
Precautions when using Mockito.anyString as an argument when Mocking with Mockito
I tried using JOOQ with Gradle
When I tried to build an environment of PHP7.4 + Apache + MySQL with Docker, I got stuck [Windows & Mac]
When registering a new user, I got an error called ActiveRecord :: NotNullViolation and how to deal with it.
I tried using Scalar DL with Docker
I made an eco server with scala
I tried using OnlineConverter with SpringBoot + JODConverter
I tried using OpenCV with Java + Tomcat
Using hidden type when PUT with Thymeleaf
Be careful when using rails_semantic_logger with unicorn
When I renew the certificate with CircleCI × fastlane, I get an exit status: 65 error.