如何模拟返回最终类的静态方法? [英] How to mock static method that returns final class?
问题描述
我想模拟下一行:
Bigquery bigquery = Transport.newBigQueryClient(options).build();
这里的问题是newBigQueryClient方法返回的Bulder类是最终的.这意味着我既不能使用嘲笑者也不可以使用powermockito来嘲笑它(它返回这样的异常:不能对最终类进行子类化),但是我需要返回适合于在其上模仿构建方法的东西.有什么想法怎么做吗?
The problem here is that newBigQueryClient method returns Bulder class, which is final. This means that I cannot mock it neither with mockito or powermockito(it returns such exception: Cannot subclass final class), but I need to return something suitable to mock build method on it. Any ideas how to do it?
推荐答案
关于改善代码并使其更具可测试性的建议:
A suggestion to improve your code and making it much more testable:
首先,您不会像您作为示例给出的作业那样模拟语句.您可以模拟对象,并将其引用分配给其类型表示超类型的变量.
First of all, you do not mock a statement like the assignment that you gave us as an example. You mock objects and assign their references to variables whose type represent a super type.
此外,如果您觉得自己必须嘲笑某些东西,那么您显然已经在代码段中找到了一个重要的依赖项.
Additionally, if you feel you have to mock something away, you have obviously found a dependency in your code snippet that is an important concept.
使这个概念显而易见!
在您的情况下,您想要获取一个Bigquery
对象并将其引用分配给变量.不清楚的概念是某人必须提供这样的对象.
In your case, you want to get a Bigquery
object and assign its reference to a variable. The unclear concept is that someone has to provide such an object.
通过界面使这个概念更清楚:
Make this concept clear with an interface:
interface BigqueryProvider {
Bigquery provide(Object options);
}
在课堂上你也有陈述
Bigquery bigquery = Transport.newBigQueryClient(options).build();
您现在添加以下实例变量
you now add the following instance variable
private final BigqueryProvider bigqueryProvider;
,并相应地更改构造函数.正如我所说的,它必须在构造时设置.当然,您还必须标识调用构造函数的代码.为此,您还需要一个默认实现:
and change your constructors accordingly. As I made it final
it must be set at construction time. Of course, you must also identify the code where you call the constructors. For that you also need a default implementation:
final class DefaultBigqueryProvider implements BigqueryProvider {
@Override
public Bigquery provide(Object options) {
return Transport.newBigQueryClient(options).build();
}
}
然后将上述分配更改为
Bigquery bigquery = bigqueryProvider.provide(options);
现在进行测试:现在,在测试中,您可以为提供程序接口提供测试实现.一个模拟框架可以轻松地为您做到这一点.您还可以返回选择的Bigquery
对象,无论该对象是该类还是子类的对象,都没有关系.
Now to the tests: In your tests, you now can provide a test implementation for the provider interface. A mocking framework can easily do that for you. You are also able to return a Bigquery
object of your choice, being it an object of that class or of a subclass, it doesn't matter.
然后,您的测试代码通过为您提供完全受控的模拟BigqueryProvider
来实例化您的类.
Your test code then instantiates your class by providing them a mocked BigqueryProvider
which you have under full control.
这篇关于如何模拟返回最终类的静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!