How to match null passed to parameter of Class<T> with Mockito
JavaUnit TestingMockingMockitoJava Problem Overview
I have methods like these:
public <T> method(String s, Class<T> t) {...}
That I need to check that null
is passed to the second argument when using matchers for the other parameters, I have been doing this :
@SuppressWarnings("unchecked")
verify(client).method(eq("String"), any(Class.class));
But is there a better way (without suppress warnings) ? T
represents the return type of some other method, which is sometimes void
and in these cases null
is passed in.
Java Solutions
Solution 1 - Java
Mockito has an isNull
matcher, where you can pass in the name of the class. So if you need to use it with other matchers, the correct thing to do is
verify(client).method(eq("String"),isNull(Class<?>.class));
This is now deprecated, see the answer below for the new method - https://stackoverflow.com/a/41250852/1348
Solution 2 - Java
Update from David Wallace's answer:
As of 2016-12, Java 8 and Mockito 2.3,
public static <T> T isNull(Class<T> clazz)
is Deprecated and will be removed in Mockito 3.0
use
public static <T> T isNull()
instead
Solution 3 - Java
This works for me:
verify(client).method(eq("String"), eq((Class<?>) null));