【发布时间】:2013-05-03 19:10:27
【问题描述】:
我可以使用 Mockito 来测试在我的对象上调用方法是否调用了超级实现吗?我找不到办法做到这一点。基本上我想要这样的东西:
@RunWith(RobolectricTestRunnerWithInjection.class)
public class TestFragmentTest {
@Spy private TestFragment testFragment;
@Test
public void onConfigurationChanged_shouldNotCallSuper() {
doThrow(new RuntimeException("Should not call super!")).when(superOf(testFragment))
.onConfigurationChanged(null);
testFragment.onConfigurationChanged(null);
}
private static class TestFragment extends Fragment {
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}
}
Mockito 中当然没有 superOf 实用程序,但这表达了我正在寻找的行为。
【问题讨论】:
-
你必须断言这个吗?听起来您的测试将与实现紧密耦合,而不是测试合同?
-
@NilsH 是正确的。这就是为什么你也应该支持组合而不是继承。
-
我同意,赞成组合而不是继承。不幸的是,我无法控制 Google 的男孩子如何决定编写他们的框架。鉴于这是试图测试 Android 代码,并且超类会执行我在这里试图避免的各种事情,而我无法对其进行断言,因此我只想确保不调用 super。
标签: android unit-testing mockito