我的類結構如下:在模擬的Java的Mockito繼承的方法
public class MyParentClass {
void doSomethingParent(){
System.out.println("something in parent");
}
}
public class MyClass extends MyParentClass{
protected String createDummyRequest(Holder myHolder){
//...
super.doSomethingParent();//I want to avoid this
//...
callingDB();
return "processedOutput";
}
private void callingDB(){
System.out.println("Calling to DB");
}
}
然後我的單元測試:
public class UnitTest {
public void testCreateDummyRequest(){
//create my mock holder
Holder mockHolder = new Holder();
MyClass mockObj = Mockito.mock(MyClass.class);
//mock doSomethingParent()
//mock callingDB()
//as mockObj is a fully mock, but I need to run my real method
//Mockito.when(mockObj.createDummyRequest(mockHolder)).thenCallRealMethod();
mockObj.createDummyRequest(mockHolder);
//Problem: doSomethingParent() is getting called though I have mocked it
}
}
如何防止)的super.doSomethingParent的調用(在我方法? (我正在寫測試的方法)
我認爲Nicktar和Serghey Bishyr的答案可能已經對你有用了,但我可能會有更多評論。 可以肯定的是:你在UnitTest類中的目標是測試MyClass的實現,但打破MyParentClass的依賴性(換句話說,測試MyClass實現爲MyParentClass提供模擬)? –