如何将传递给 Class < T > 参数的 null 与 Mockito 匹配

我有这样的方法:

public <T> method(String s, Class<T> t) {...}

在使用其他参数的匹配器时,我需要检查 null是否被传递给第二个参数,我一直在这样做:

@SuppressWarnings("unchecked")
verify(client).method(eq("String"), any(Class.class));

但是,有没有更好的方法(不压制警告) ?T表示某些其他方法的返回类型,有时是 void,在这些情况下传入 null

77539 次浏览

This works for me:

verify(client).method(eq("String"), eq((Class<?>) null));

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