Matchers.any()在Mockito中为空值 [英] Matchers.any() for null value in Mockito
问题描述
假设我有这个对象objectDemo,它使用2个参数String和null调用方法objectDemoMethod.现在,我想验证此方法是否已通过Mockito调用:
Suppose I am having this object objectDemo which calls to the method objectDemoMethod with 2 parameters String and null. Now I want to verify that this method was called with Mockito:
objectDemo.objectDemoMethod("SAMPLE_STRING", null);
我写了这个:
Mockito.verify(objectDemo, Mockito.times(1)).objectDemoMethod(Matchers.any(String.class), null);
但是出现错误:
无效使用参数匹配器来获取空值.
Invalid use of argument matchers for null value.
还有其他方法可以传递空值吗?
Is there any another way to pass null value?
推荐答案
由于您仅对一个参数使用参数匹配器,而对另一个参数不使用参数匹配器,因此会出现错误消息.来自 Matchers
Javadoc:
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.
因此,解决方法是也将匹配器用于方法的第二个参数.在这种情况下,它将是匹配null
的匹配器.根据Mockito和Java的版本,您可以:
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());
请注意,如果您使用的是Java 7或更早版本,则需要显式强制转换才能完成此工作,因为这些Java版本中的类型推断未考虑称为以下方法的类型:
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));
对于Java≤在7种情况下,或在Mockito 1情况下,这些示例使用的情况是第二个参数的类型为String
:需要将其替换为方法参数的实际类型.
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.
这篇关于Matchers.any()在Mockito中为空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!