gpt4 book ai didi

java - 模拟继承的 final方法

转载 作者:行者123 更新时间:2023-11-30 06:53:20 25 4
gpt4 key购买 nike

我有两个类:

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。我对同一个模拟对象的其他方法调用按预期使用 when/return 模式工作,所以我玩弄了多态性。当我删除对方法的最终限制并在派生类中覆盖它(只是调用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com