本文介紹了例外:mockito 想要但沒有被調(diào)用,實際上與這個 mock 的交互為零的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我有界面
Interface MyInterface {
myMethodToBeVerified (String, String);
}
接口的實現(xiàn)是
class MyClassToBeTested implements MyInterface {
myMethodToBeVerified(String, String) {
…….
}
}
我還有一門課
class MyClass {
MyInterface myObj = new MyClassToBeTested();
public void abc(){
myObj.myMethodToBeVerified (new String("a"), new String("b"));
}
}
我正在嘗試為 MyClass 編寫 JUnit.我已經(jīng)完成了
I am trying to write JUnit for MyClass. I have done
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
}
但是我得到 mockito 想要但沒有被調(diào)用,實際上在驗證調(diào)用時與這個 mock 的交互為零.
誰能提出一些解決方案.
can anyone suggest some solutions.
推薦答案
你需要在你正在測試的類中注入 mock.目前,您正在與真實對象進行交互,而不是與模擬對象進行交互.您可以通過以下方式修復(fù)代碼:
You need to inject mock inside the class you're testing. At the moment you're interacting with the real object, not with the mock one. You can fix the code in a following way:
void testAbc(){
myClass.myObj = myInteface;
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
雖然將所有初始化代碼提取到 @Before
although it would be a wiser choice to extract all initialization code into @Before
@Before
void setUp(){
myClass = new myClass();
myClass.myObj = myInteface;
}
@Test
void testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
這篇關(guān)于例外:mockito 想要但沒有被調(diào)用,實際上與這個 mock 的交互為零的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!