問題描述
我在一些測試中使用了 Mockito.
I'm using Mockito in some tests.
我有以下課程:
class BaseService {
public void save() {...}
}
public Childservice extends BaseService {
public void save(){
//some code
super.save();
}
}
我只想模擬 ChildService
的第二次調用 (super.save
).第一次調用必須調用真正的方法.有沒有辦法做到這一點?
I want to mock only the second call (super.save
) of ChildService
. The first call must call the real method. Is there a way to do that?
推薦答案
不,Mockito 不支持這個.
No, Mockito does not support this.
這可能不是您要尋找的答案,但您看到的是未應用設計原則的癥狀:
This might not be the answer you're looking for, but what you're seeing is a symptom of not applying the design principle:
優先組合優于繼承
如果您提取策略而不是擴展超類,問題就消失了.
If you extract a strategy instead of extending a super class the problem is gone.
如果你不被允許更改代碼,但無論如何你必須測試它,并且以這種尷尬的方式,仍然有希望.使用一些 AOP 工具(例如 AspectJ),您可以將代碼編織到超類方法中并完全避免其執行(糟糕).如果您使用代理,這不起作用,您必須使用字節碼修改(加載時編織或編譯時編織).也有一些模擬框架支持這種類型的技巧,例如 PowerMock 和 PowerMockito.
If however you are not allowed to change the code, but you must test it anyway, and in this awkward way, there is still hope. With some AOP tools (for example AspectJ) you can weave code into the super class method and avoid its execution entirely (yuck). This doesn't work if you're using proxies, you have to use bytecode modification (either load time weaving or compile time weaving). There are be mocking frameworks that support this type of trick as well, like PowerMock and PowerMockito.
我建議您進行重構,但如果這不是一個選項,您可以享受一些嚴肅的黑客樂趣.
I suggest you go for the refactoring, but if that is not an option you're in for some serious hacking fun.
這篇關于Mockito 如何僅模擬超類方法的調用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!