[英]Mockito with @Mock and @InjectMock Wanted but not invoked: Actually, there were zero interactions with this mock
[英]Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock
我有接口
Interface MyInterface {
myMethodToBeVerified (String, String);
}
接口的實現是
class MyClassToBeTested implements MyInterface {
myMethodToBeVerified(String, String) {
…….
}
}
我還有一個 class
class MyClass {
MyInterface myObj = new MyClassToBeTested();
public void abc(){
myObj.myMethodToBeVerified (new String(“a”), new String(“b”));
}
}
我正在嘗試為 MyClass 編寫 JUnit。 我已經做好了
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String(“a”), new String(“b”));
}
}
但是我得到了mockito wanted but not invoked,實際上在驗證調用時與這個模擬的交互為零。
誰能提出一些解決方案。
您需要在您正在測試的類中注入模擬。 目前您正在與真實對象交互,而不是與模擬對象交互。 您可以通過以下方式修復代碼:
void testAbc(){
myClass.myObj = myInteface;
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
盡管將所有初始化代碼提取到@Before
是一個更明智的選擇
@Before
void setUp(){
myClass = new myClass();
myClass.myObj = myInteface;
}
@Test
void testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
您的類MyClass
創建一個新的MyClassToBeTested
,而不是使用您的模擬。我在 Mockito wiki 上的文章描述了兩種處理方法。
@Jk1 的回答很好,但 Mockito 還允許使用注釋進行更簡潔的注入:
@InjectMocks MyClass myClass; //@InjectMocks automatically instantiates too
@Mock MyInterface myInterface
但是無論您使用哪種方法,都不會處理注釋(甚至不是您的 @Mock),除非您以某種方式調用靜態MockitoAnnotation.initMocks()
或使用@RunWith(MockitoJUnitRunner.class)
注釋該類。
@jk1 的回答很完美,既然@igor Ganapolsky 問,為什么我們不能在這里使用 Mockito.mock? 我發布這個答案。
為此,我們為 myobj 提供了一個 setter 方法,並使用模擬對象設置 myobj 值。
class MyClass {
MyInterface myObj;
public void abc() {
myObj.myMethodToBeVerified (new String("a"), new String("b"));
}
public void setMyObj(MyInterface obj)
{
this.myObj=obj;
}
}
在我們的 Test 類中,我們必須編寫以下代碼
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
@test
testAbc() {
myclass.setMyObj(myInterface); //it is good to have in @before method
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
}
如果說您希望 thisMethod() 執行,但它沒有執行,也可以拋出此異常。 不是因為它處於未滿足的條件內。
例如,如果您有一些單元測試說 verify thisMethod() 已執行,但實際上並不是因為 varX 和 varY 不相等。
//method expected to be called.
if( varX == varY){
thisMethod();
}
//test
Mockito.verify(foo).thisMethod();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.