Avinash Jadhav Avinash Jadhav - 11 months ago 422
Java Question

Matchers.any() for null value in Mockito

Suppose I am having this object objectDemo which calls to the method objectDemoMethod with 2 parameters String and null. Now I want to verify that this method was called with Mockito:

objectDemo.objectDemoMethod("SAMPLE_STRING", null);

I have written this:

Mockito.verify(objectDemo, Mockito.times(1)).objectDemoMethod(Matchers.any(String.class), null);

but it's giving an error:

Invalid use of argument matchers for null value.

Is there any another way to pass null value?


You can use Mockito Matchers.isNull matcher:

verify(objectDemo, times(1)).objectDemoMethod(any(String.class), isNull(String.class));

isNull is given as parameter the class of the expected method type. I took the example of String here but you should replace it with what your method is declaring as second parameter.

The error message you are getting is expected since you are using argument matcher for only one argument and not the other. From Matchers Javadoc:

If you are using argument matchers, all arguments have to be provided by matchers.