java - 模拟继承的 final方法

标签 java junit mockito

我有两门课:

public class BaseClass <T> {
  private final T config;
  ...
  @NotNull
  public final T getConfig() {
    return config;
  }
}

public class DerivedClass extends BaseClass<MyConfig> {
  ...
}

还有一个测试:

...
MyConfig myConfig = mock(MyConfig.class);
DerivedClass child = mock(DerivedClass.class);
when(child.getConfig()).thenReturn(myConfig); // this line generates the error

我收到一个错误,指出 getConfig() 返回 null,而不是 myConfig。我对同一个模拟对象进行了其他方法调用,按预期使用时间/返回模式,因此我使用了多态性。当我删除对该方法的最终限制并在派生类中覆盖它(仅调用 super 版本)时,模拟工作正常。

我不想为了测试而重新设计产品代码并降低 API 的刚性,因此上面的继承更改不是一个可接受的解决方案。如何模拟对父类(super class)方法的调用?

最佳答案

来自Mockito's FAQ :

What are the limitations of Mockito?
[...]

  • Cannot mock final methods - their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.

[...]

为此,您需要像 PowerMock 这样的扩展名。请参阅this question一个工作示例。完整的描述可以在 PowerMock's documentation 中找到。

关于java - 模拟继承的 final方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37712127/

相关文章:

java - 手机关机后重新启动

java - 如何使用 Java 以编程方式停止和启动 Appium 服务器?

java - 为什么ArrayList的非静态内部类SubList有一个成员变量 "parent"?

android - 使用mockito测试void方法

android - 如何在Android项目中使用PowerMock?

Java:验证 null 方法参数的最佳方法是什么

eclipse - eclipse 项目中 junit 和 source 的两个独立 JRE

unit-testing - java.lang.IncompleteClassChangeError org.junit.jupiter.params.provider.Arguments 必须是 InterfaceMethodref 常量

java - 正在使用 Assert.assertTrue(true);并断言 Assert.fail(); JUnit 测试的良好实践?

unit-testing - 如何在 repo 中测试/模拟 Hive (Flutter) 打开框逻辑?