【问题标题】:Use Mockito to test that super was not called使用 Mockito 测试 super 未被调用
【发布时间】: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


【解决方案1】:

这样做的一种方法是在超类中放置一个特殊变量,该变量仅在您在子类中调用的构造函数中初始化。

这样您可以添加一个函数来检查超类中的变量是否已更改。

【讨论】:

  • 超类不是我要编辑的。这是 Android 框架代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多