Any()表示 Mockito 的 null 值

假设我有这样一个对象 objectDemo,它调用具有2个参数 Stringnull的方法 objectDemoMethod。现在我想和 Mockito 验证一下这个方法是否被调用:

objectDemo.objectDemoMethod("SAMPLE_STRING", null);

我这样写道:

Mockito.verify(objectDemo, Mockito.times(1)).objectDemoMethod(Matchers.any(String.class), null);

但它给出了一个错误:

对空值使用参数匹配器无效。

还有其他传递 null值的方法吗?

141720 次浏览

The error message you are getting is expected since you are using argument matcher for only one argument and not the other. From Matchers Javadoc:

If you are using argument matchers, all arguments have to be provided by matchers.

Therefore, the fix is to use a matcher for the second parameter of the method as well. In this case, it would be a matcher matching null. Depending on the version of Mockito and Java, you can have:

  • Starting with Mockito 2, you can use ArgumentMatchers.isNull(). This works with Java 8 and above:

    verify(objectDemo, times(1)).objectDemoMethod(any(String.class), isNull());
    

    Note that if you're running with Java 7 or older, you'll need an explicit cast to make this work, because the type inference in those versions of Java does not take into account the types of the method called:

    verify(objectDemo, times(1)).objectDemoMethod(any(String.class), (String) isNull());
    
  • If you're using Mockito 1, you can use the Matchers.isNull(clazz) instead:

    verify(objectDemo, times(1)).objectDemoMethod(any(String.class), isNull(String.class));
    

For the Java ≤ 7 or Mockito 1 cases, the examples uses a case where the second parameter was of type String: it would need to be replaced with the actual type of the method parameter.

isNull seems to be deprecated

With Java 8 this method will be removed in Mockito 3.0. This method is only used for generic friendliness to avoid casting, this is not anymore needed in Java 8.

I think you could use nullable:

  • public static <T> T nullable(Class<T> clazz)

You could use something like:

verify(objectDemo, times(1)).objectDemoMethod(any(String.class), nullable(String.class));

Just use:

Mockito.verify(objectDemo, Mockito.times(1)).objectDemoMethod(Matchers.any(String.class), (ClassName) isNull());

Above help me in java 8 version. Hope this will help you.

You can make use of Mockito's ArgumentMatchers class, like so:

Mockito.verify(objectDemo).objectDemoMethod(ArgumentMatchers.any(String.class), ArgumentMatchers.isNull());

Ran into this when using Mockito 2.28 and Mockito Kotlin 2.2

any() and isNull() weren't matching. However, eq(null) did finally match, so you might try that if you're in the same boat.