问题描述
我在一些测试中使用了 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 如何仅模拟超类方法的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!