0

我有一个类初始化为私有类变量

public class MyClass{

    private BusinessObject businessObject = BusinessObjectGenerator.getBusinessObject();

    public MyClass(){

    }

    public Object myMethodToTest(){
    return businessObject.getObject();
    }
}

现在,我正在尝试进行单元测试,myMethodToTest我想发送一个模拟对象来代替businessObject. 我使用 mockito 进行模拟并spy(new MyClass())用于部分模拟,但在模拟 get 调用时遇到了麻烦businessObject。1.是否可以模拟对businessObject的调用?如果有怎么办?2.在编写单元测试时如何重构此代码以提供帮助。任何指向这一点的资源都会有很大帮助。

谢谢!

4

1 回答 1

4

要正确重构此代码,您需要:

private BusinessObject businessObject;

public void setBusinessObject(BusinessObject instance) {
    businessObject = instance;
}

private BusinessObject getBusinessObject() {
    if (businessObject == null) {
        // represents existing implementation in original code sample
        businessObject = BusinessObjectGenerator.getBusinessObject();
    }
    return businessObject;
}

/* rest of your code */

现在您可以在测试站点自己将您的模拟注入到课程中。

我建议使用像Guice这样的框架的依赖注入来做到这一点。这将是值得您花时间的。

于 2012-11-30T04:10:52.110 回答