问题描述
是否可以使用Mockito和可选的Powermock模拟超类 S
,以便对超类的任何调用 S
(包括对 S()
构造函数的调用)是否被模拟?因此,使用下面的示例,如果我使用Mockito将 S
替换为 MockS
,则会调用 super()
使用 MockS
中的构造函数?
Is it possible using Mockito and optionally Powermock to mock a superclass S
such that any calls to the superclass to S
(including calls to the S()
constructor) are mocked? So using the below example, if I replace S
with MockS
using Mockito, will the call to super()
use the constructor in MockS
?
class S {
S() {
// Format user's hard drive, call 911, and initiate self-destruct
}
}
class T extends S {
T() {
super();
}
}
class Test {
@Mock private S mockS;
new T(); // T's call to super() should call the mock, not the destructive S.
}
S 中模拟单个方法或仅模拟对 super()
的调用的问题,并阅读这是不受支持的,但我不清楚我是否可以模拟整个超类。
I've seen questions about mocking individual methods in S
or mocking only calls to super()
, and read that this is unsupported, but it's not clear whether or not I can mock the entire superclass.
使用我当前的测试,当我尝试模拟 S
时, T
调用 super()
调用实际实现,而不是模拟。
With my current tests, when I try to mock S
, T
's call to super()
calls the real implementation, not the mock.
推荐答案
为了解决这个明显的限制,我重构了我的代码,,我认为我最终得到了更好的设计,因为继承并不是必需的。
To work around this apparent limitation, I refactored my code, replacing inheritance with delegation, and I think I've ended up with a better design anyhow since the inheritance wasn't really necessary.
新代码看起来像这样。请注意,问题的代码已经简化,因此真正的类具有更多功能。
The new code looks like this. Mind you the code for the question was simplified, so the real classes have much more functionality.
class S {
S() {
// Format user's hard drive, call 911, and initiate self-destruct
}
}
class T {
T(S s) {} // Now T "has an S" instead of "is an S"
}
class Test {
@Mock private S mockS;
new T(s); // T's call to super() should call the mock, not the destructive S.
}
For those interested, using Guice and Android, the test looks more like this:
class T {
T(Activity activity, S s) {}
}
class Test {
@Mock Activity activity;
@Mock S mockS;
injector = Guice.createInjector(new AbstractModule() {
@Override protected void configure() {
bind(Activity.class).toInstance(activity);
bind(S.class).toInstance(mockS);
}}
);
T t = injector.getInstance(T.class);
}
这篇关于我可以用Mockito / Powermock模拟一个超类的构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!