发出在java中模拟类变量值的问题

时间:2012-11-30 03:45:18

标签: java unit-testing junit refactoring mockito

我有一个类,其初始化类似于

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.如何在编写单元测试时重构此代码以帮助解决问题。任何指向这方面的资源都会有很大的帮助。

谢谢!

1 个答案:

答案 0 :(得分: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这样的框架进行依赖注入。值得你花时间。