問題描述
有時當我編寫單元測試時,我應該模擬對超類的引用.
Sometimes when I write unit tests I should to mock reference to superclass.
我讀過這個問題:問題
此答案answer with DI 建議重構代碼.但我做不到
This answer answer with DI advice to refactor code. But I cannot it
如果超類方法足夠大,則此答案另一個答案不適合.就我而言,我有非常大的代碼.是的,我知道它違反了 SOLID OOD 原則,但我應該編寫測試.我沒有足夠的時間進行重構.
this answer another answer is not suitable if superclass method is enough big. In my case I have very big code. Yes I know that it is brokes SOLID OOD principes but I just should to write test. I have not enough time for refactor.
該問題是 4 年前提出的!
said question was asked 4 years ago!
目前 Mockito 或 Powermock 是否可以解決此問題?
Does currently Mockito or Powermock can resolve this issue ?
代碼示例:
class BaseService {
public void save() {
// a lot of code here! I cannot change this code.
}
}
public Childservice extends BaseService {
public void save(){
//logic for testing
super.save();
//logic for testing
}
}
更新 2
public class Parent {
public int save() {
return 99;
}
}
public class Child extends Parent {
public int save() {
int i = super.save();
return i*2;
}
}
和測試:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Parent.class)
public class ParentTest {
@Test
public void testSave() {
PowerMockito.suppress(PowerMockito.methodsDeclaredIn(Parent.class));
System.out.println(new Child().save());
}
}
輸出:198
推薦答案
使用 Powermock 您可以替換或抑制方法,因此可以更改 BaseService.save()
完成的操作.您還可以使方法對抑制不做任何事情.您甚至可以抑制靜態初始化程序塊.
With Powermock you can replace or suppress methods, so it is possible to change the action done by BaseService.save()
. You can also make methods to do nothing with suppressing. You can even suppress static initializer blocks.
請閱讀 Powermock 作者的這篇博文.請參閱更換"一章.
Please read this blog entry of the Powermock authors. See chapter "Replacing".
更新:
抑制似乎對我有用,但替換不行.見下圖:
Suppress seems to work for me, but replace not. See the picture below:
這篇關于如何模擬超級參考(在超級類上)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!