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

JavaUnit TestingMockingMockito

Java 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));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionblankView Question on Stackoverflow
Solution 1 - JavaDawood ibn KareemView Answer on Stackoverflow
Solution 2 - Javamike rodentView Answer on Stackoverflow
Solution 3 - JavaEricView Answer on Stackoverflow