問(wèn)題描述
我在一些測(cè)試中使用了 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
的第二次調(diào)用 (super.save
).第一次調(diào)用必須調(diào)用真正的方法.有沒(méi)有辦法做到這一點(diǎn)?
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 不支持這個(gè).
No, Mockito does not support this.
這可能不是您要尋找的答案,但您看到的是未應(yīng)用設(shè)計(jì)原則的癥狀:
This might not be the answer you're looking for, but what you're seeing is a symptom of not applying the design principle:
優(yōu)先組合優(yōu)于繼承
如果您提取策略而不是擴(kuò)展超類(lèi),問(wèn)題就消失了.
If you extract a strategy instead of extending a super class the problem is gone.
如果你不被允許更改代碼,但無(wú)論如何你必須測(cè)試它,并且以這種尷尬的方式,仍然有希望.使用一些 AOP 工具(例如 AspectJ),您可以將代碼編織到超類(lèi)方法中并完全避免其執(zhí)行(糟糕).如果您使用代理,這不起作用,您必須使用字節(jié)碼修改(加載時(shí)編織或編譯時(shí)編織).也有一些模擬框架支持這種類(lèi)型的技巧,例如 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.
我建議您進(jìn)行重構(gòu),但如果這不是一個(gè)選項(xiàng),您可以享受一些嚴(yán)肅的黑客樂(lè)趣.
I suggest you go for the refactoring, but if that is not an option you're in for some serious hacking fun.
這篇關(guān)于Mockito 如何僅模擬超類(lèi)方法的調(diào)用的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!