我有两门课:
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/