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.
Since Mockito any(Class) and anyInt family matchers perform a type check, thus they won't match null arguments. Instead use the isNull matcher.
Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo. class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.
Mockito uses equal() as a legacy method for verification and matching of argument values. In some cases, we need more flexibility during the verification of argument values, so we should use argument matchers instead of equal() method. The ArgumentMatchers class is available in org. mockito package.
Mockito Argument Matcher - eq() When we use argument matchers, then all the arguments should use matchers. If we want to use a specific value for an argument, then we can use eq() method. when(mockFoo. bool(eq("false"), anyInt(), any(Object.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With