模拟外部不可见的依赖项
我必须对一些旧代码进行单元测试,这些代码并非旨在支持单元测试(无 DI)。有没有办法模拟在公共方法中初始化的对象?
public int method() {
A a = new A(ar1, arg2); //How to mock this?
}
谢谢,
-阿比迪
I have to unit test some old code that wasn't designed to support unit testing (No DI). Is there a way to mock an object that is being initialized within a public method?
public int method() {
A a = new A(ar1, arg2); //How to mock this?
}
Thanks,
-Abidi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种选择是将代码重构为
在您的测试方法中,现在您可以使用 Mockito 的
spy
和doAnswer
函数来覆盖测试装置上的createA
大致如下:Another option is to refactor the code into
In your test method now you can use Mockito's
spy
anddoAnswer
functions to overridecreateA
on your test fixture with something along the lines of:如果您可以控制相关代码,则可以重构它并使依赖项公开,例如通过依赖某个 A-builder。这可能是最好的解决方案,因为它使您的类减少对
A
的依赖。 [强制您解耦设计是测试的主要优点之一。]If you have control over the code in question, you can refactor it and make the dependency public, for example by depending on some A-builder. This is probably the best solution, since it makes your class less dependent on
A
. [Forcing you to decouple your design is one of the main advantages of testing.]