問題描述
我正在嘗試編寫一個單元測試,為此我正在為 Mockito 模擬編寫一個 when 語句,但我似乎無法讓 eclipse 認識到我的返回值是有效的.
I'm trying to write a unit test, and to do that I'm writing a when statement for a Mockito mock, but I can't seem to get eclipse to recognize that my return value is valid.
這就是我正在做的事情:
Here's what I'm doing:
Class<?> userClass = User.class;
when(methodParameter.getParameterType()).thenReturn(userClass);
.getParameterType()
的返回類型是Class<?>
,所以不明白eclipse為什么說,方法thenReturn(Class<capture#1-of ?>) 類型為 OngoingStubbing<Class<capture#1-of ?>>不適用于參數 (Class<capture#2-of ?>)
.它提供了轉換我的 userClass,但這只會使一些亂碼 eclipse 說它需要再次轉換(并且不能轉換).
The return type of .getParameterType()
is Class<?>
, so I don't understand why eclipse says, The method thenReturn(Class<capture#1-of ?>) in the type OngoingStubbing<Class<capture#1-of ?>> is not applicable for the arguments (Class<capture#2-of ?>)
. It offers to cast my userClass, but that just makes some garbled stuff eclipse says it needs to cast again (and can't cast).
這只是 Eclipse 的問題,還是我做錯了什么?
Is this just an issue with Eclipse, or am I doing something wrong?
推薦答案
另外,一個更簡潔的解決方法是使用 do 語法而不是 when.
Also, a slightly more terse way to get around this is to use the do syntax instead of when.
doReturn(User.class).when(methodParameter).getParameterType();
這篇關于無法使用 Mockito 返回類對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!