模拟类的直接实例化 [英] Mock direct instantiation of classes

查看:85
本文介绍了模拟类的直接实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常遇到模拟类的直接实例化的问题:

final File configFile = new File(pathFile);

我想模拟new File(pathFile)以制作doReturn(otherFile).

我发现我可以通过将其包装在另一种方法中来模拟直接实例化.我不想通过创建仅用于单元测试的实例化方法来修改我的所有代码,这很丑陋.

还有其他方法吗?

解决方案

在理想情况下,您的方法调用是不透明的:影响它的唯一方法是更改​​其状态,依赖项或参数.构造函数本质上是静态方法调用,在Java中没有提供重写或调整行为的机会.构造函数也可能是内联的,并且在某些可能确实发生的虚拟机上.

除了为自己创建测试接缝"(例如工厂对象或可重写方法)外,您唯一的选择是在编译类和在测试中运行之间编辑字节码. ,是 PowerMock所做的,如默认语言环境的注释中所述.尽管PowerMock是一个功能强大且有用的库,但它确实具有一些非常具体的安装步骤,可能很难正确完成,然后您要测试PowerMock编辑的被测类而不是类本身. /p>

有关相关问题(如何在私有字段中模拟实例),请参见此答案.具体结果有所不同,但是类似地,您必须重构以进行测试或破坏封装.

I'm often confronted with the problem of mocking direct instantiations of classes:

final File configFile = new File(pathFile);

I'd like to mock new File(pathFile) in order to make a doReturn(otherFile).

I found that I could mock the direct instantiation by wrapping it in another method. Thing is I don't want to amend all my code by creating methods for instantiations just for unit testing, that would be ugly.

Is there any other way?

解决方案

Under ideal circumstances, your method call is opaque: The only way you can influence it is to change its state, dependencies, or parameters. Constructors are inherently static method calls, which provide no opportunity (in Java) for overriding or adjusting behavior. The constructor might as well be inlined, and on some virtual machines that may literally happen.

Other than creating a testing "seam" for yourself, such as a factory object or overridable method, your only other choice is to edit the bytecode between when the class is compiled and when it is run in your test—which, incidentally, is what PowerMock does as in default locale's comment. Though PowerMock is a powerful and useful library, it does have some extremely specific installation steps that can be tricky to get right, and then you're testing the PowerMock-edited version of your class-under-test rather than the class itself.

See this answer for a related question (how to mock an instance in a private field). The specific outcome is different, but similarly you have to either refactor for testing or break encapsulation.

这篇关于模拟类的直接实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆