Mockito Matchers.any(...) on one argument only

Kevvvvyp picture Kevvvvyp · Apr 27, 2015 · Viewed 7.6k times · Source

I want to do this:

 verify(function, Mockito.times(1)).doSomething(argument1, Matchers.any(Argument2.class));

Where argument1 is a specfic instance of type Argument1 and argument2 is any instance of the type Argument2.

But I get an error:

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

Following that advice I can write the following and everything is fine:

 verify(function, Mockito.times(1)).doSomething(Matchers.any(Argument1.class), Matchers.any(Argument2.class));

Where I am looking for any arguement of type Argument1 and any argument of type Argument2.

How can I acheive this desired behaviour?

Answer

fge picture fge · Apr 27, 2015

There is more than one possible argument matcher and one is eq, which is mentioned in the exception message. Use:

verify(function, times(1)).doSomething(eq(arg1), any(Argument2.class));

(static imports supposed to be there -- eq() is Matchers.eq()).

You also have same() (which does reference equality, ie ==), and more generally you can write your own matchers.