Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 889
Kevvvvyp Avatar asked Apr 27 '15 13:04

Kevvvvyp


People also ask

Does Mockito any () match null?

Since Mockito any(Class) and anyInt family matchers perform a type check, thus they won't match null arguments.

What can I use instead of Mockito matchers?

org. mockito. Matchers is deprecated, ArgumentMatchers should be used instead.

Does any () match null?

anyString() does not work for null #185.

What is the use of Mockito Any ()?

Mockito allows us to create mock objects and stub the behavior for our test cases. We usually mock the behavior using when() and thenReturn() on the mock object.


1 Answers

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.

like image 116
fge Avatar answered Sep 23 '22 12:09

fge