問題描述
我有一個接口,它帶有一個需要 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 開始,您可以使用無參數的 any
方法,編譯器會推斷類型參數:
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.
添加此機制主要是為了能夠編譯 lambda 表達式,但它總體上改進了類型推斷.
This mechanism was added mainly to be able to compile lambda expressions, but it improves type inferences generally.
不幸的是,這不適用于原始類型:
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
.在將返回值傳遞給 doStuff
之前,運行時將嘗試通過調用 intValue
方法將返回值拆箱,并引發異常.
The problem is that the compiler will infer Integer
as the return value type 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()";方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!