使用 spy 模拟在测试的类中创建的完整对象 [英] Using spy to mock a full object created in the class which is tested

查看:75
本文介绍了使用 spy 模拟在测试的类中创建的完整对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构:

class A {

    public A(String p){
        // ...
    }

    public String AMethod(String p){
        // ...
    }

}

class B {
    int method(String param){
        A a = new A(param); int n;
        String s = A.AMethod(param);
        // ... (initializes n, ...)
        return n;
    }
}

现在我想在 B 类中测试 method 但在调用时控制 AMethod 的输出.但是由于我没有在B的测试类中创建对象A,所以无法正常mock它——我该如何mock对象A呢?

Now I want to test method in class B but control the output of AMethod when it is called. But since I do not create the object A in the test class of B, I cannot mock it normally - how can I mock object A instead?

我试过 Mockito.spy 但它似乎不起作用:

this.ASpy = spy(new A());

when(ASpy.createSession(any())).then(invocation -> {
    // ... (*)
});

(*) 仍然没有被调用...但是 spy 应该是正确的解决方案,不是吗?我的问题是:我从来没有在我的测试类中创建对象 A,只有在 method 中创建了这样的对象,但不在测试类中.

(*) still doen't get called... but spy should be the right solution, shouldn't it? My problem is: I never create an object A in my test class, only in method such an object is created but not in the test class.

推荐答案

处理这个问题的最好方法(如果可能的话)是修改类 B 的代码,以便将对象 A 注入到方法中(作为参数传递),设置为类字段或使用工厂类实例化 - 工厂将作为字段注入,工厂对象可以在测试中模拟以返回模拟对象 A).

The best way to handle this (if possible) would be to modify the code of class B so that object A was injected into the method (passed as a parameter, set as a class field or instantiated with usage of a factory class - the factory would be injected as a field and the factory object could be mocked in the test to return a mocked object A).

如果实际的代码修改是不可能的,你可以使用 PowerMock 的 whenNew 方法 并在您的测试中返回一个模拟对象.

If actual code modifications are not possible, you could use PowerMock's whenNew method and return a mocked object in your test.

附注:如果您使用的是 JUnit 5,PowerMock 可能不是一个可行的解决方案 - 阅读更多 此处.

A side note: if you're using JUnit 5, PowerMock may not be a viable solution - read more here.

这篇关于使用 spy 模拟在测试的类中创建的完整对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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