phantipa
phantipa

Reputation: 49

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:Misplaced argument matcher

My code

@Path("/apiajax/*/*")
@GET
public String handleFooJson(@Context UriInfo context) {
    return null;
}

My test is

Mockito.when(Bar.handleFooJson(Mockito.any(UriInfo.class))).thenReturn(null);

I got error

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Misplaced argument matcher detected here: Mockito.when(Bar.handleFooJson(Mockito.any(UriInfo.class))).thenReturn(null); 

You cannot use argument matchers outside of verification or stubbing.

    Examples of correct usage of argument matchers:

    when(mock.get(anyInt())).thenReturn(null);
    doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
    verify(mock).someMethod(contains("foo"))

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

I don't understand the description. How I test it correctly?

Upvotes: 0

Views: 4468

Answers (2)

Saurabh Raoot
Saurabh Raoot

Reputation: 1411

Incase if you have final method in class which you are mocking then

We need to add a text file to the project's src/test/resources/mockito-extensions directory named org.mockito.plugins.MockMaker and add a single line of text:

mock-maker-inline

please refer article https://www.baeldung.com/mockito-final

Upvotes: 0

nzCharlie
nzCharlie

Reputation: 36

I don't have enough point to add comment, but I would like to add that, please check you are mocking some method that can be mocked. Please read that in the error,

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

Also static method cannot be mocked, which I think is the case here.

Mockito.when(Bar.handleFooJson(Mockito.any(UriInfo.class))).thenReturn(null);

Bar look like a Class not an object.

Upvotes: 2

Related Questions