模拟外部不可见的依赖项

发布于 2024-11-14 23:07:57 字数 190 浏览 3 评论 0原文

我必须对一些旧代码进行单元测试,这些代码并非旨在支持单元测试(无 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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

潇烟暮雨 2024-11-21 23:07:57

另一种选择是将代码重构为

public int method() {
   A a = createA(arg1,arg2);
}

A createA(int arg1, int arg2) {
    return new A(arg1,arg2);
}

在您的测试方法中,现在您可以使用 Mockito 的 spydoAnswer 函数来覆盖测试装置上的 createA大致如下:

Foo foo = new Foo();
Foo spiedFoo = spy(foo); // a spied version when you can copy the behaviour
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock inv) throws Throwable {
        A a = mock(A.class);
        return a;
    }
}).when(mySpy).createA(anyInt(), anyInt());

Another option is to refactor the code into

public int method() {
   A a = createA(arg1,arg2);
}

A createA(int arg1, int arg2) {
    return new A(arg1,arg2);
}

In your test method now you can use Mockito's spy and doAnswer functions to override createA on your test fixture with something along the lines of:

Foo foo = new Foo();
Foo spiedFoo = spy(foo); // a spied version when you can copy the behaviour
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock inv) throws Throwable {
        A a = mock(A.class);
        return a;
    }
}).when(mySpy).createA(anyInt(), anyInt());
八巷 2024-11-21 23:07:57

如果您可以控制相关代码,则可以重构它并使依赖项公开,例如通过依赖某个 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.]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文