使用Mockito的通用“any()”方法 [英] Using Mockito's generic "any()" method
问题描述
我有一个接口,其方法需要一个 Foo
的数组:
I have an interface with a method that expects an array of Foo
:
public interface IBar {
void doStuff(Foo[] arr);
}
我使用Mockito嘲笑这个界面,我想断言调用 doStuff()
,但我不想验证传递的参数是什么 - 不关心。
I am mocking this interface using Mockito, and I'd like to assert that doStuff()
is called, but I don't want to validate what argument are passed - "don't care".
如何使用 any()
(泛型方法)而不是 anyObject()
?
How do I write the following code using any()
, the generic method, instead of anyObject()
?
IBar bar = mock(IBar.class);
...
verify(bar).doStuff((Foo[]) anyObject());
推荐答案
从Java 8开始,您可以使用无参数任何
方法,类型参数将由编译器推断:
Since Java 8 you can use the argument-less any
method and the type argument will get inferred by the compiler:
verify(bar).doStuff(any());
说明
Java 8中的新东西是目标类型 将用于推断其子表达式的类型参数。在Java 8之前,只有用于类型参数推断的方法的参数(大多数时候)。
Explanation
The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).
在这种情况下,参数类型 doStuff
将是 any()
的目标类型,返回值类型为 any()
将被选择匹配该参数类型。
In this case the parameter type of doStuff
will be the target type for any()
, and the return value type of any()
will get chosen to match that argument type.
不幸的是,这不适用于原始类型:
This doesn't work with primitive types, unfortunately:
public interface IBar {
void doPrimitiveStuff(int i);
}
verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException
verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead
问题是编译器会推断出 Integer
作为 any()
的返回值。 Mockito不会意识到这一点(由于类型擦除)并返回引用类型的默认值,即 null
。运行时将尝试通过调用 intValue
方法来取消返回值,然后将其传递给 doStuff
,并且异常被抛出。
The problem is that the compiler will infer Integer
as the return value of any()
. Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is null
. The runtime will try to unbox the return value by calling the intValue
method on it before passing it to doStuff
, and the exception gets thrown.
这篇关于使用Mockito的通用“any()”方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!