Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match null passed to parameter of Class<T> with Mockito

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.

like image 627
blank Avatar asked Oct 03 '12 11:10

blank


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. Instead use the isNull matcher.

Can the Mockito Matcher methods be used as return values?

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.

How do you use argument matchers in Mockito?

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.

What is EQ Mockito?

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.


2 Answers

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

like image 133
Dawood ibn Kareem Avatar answered Oct 13 '22 03:10

Dawood ibn Kareem


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

like image 31
mike rodent Avatar answered Oct 13 '22 01:10

mike rodent