我有一个初始化的私有类变量的类,如下所示
public class MyClass{
private BusinessObject businessObject = BusinessObjectGenerator.getBusinessObject();
public MyClass(){
}
public Object myMethodToTest(){
return businessObject.getObject();
}
}
现在,我正在尝试单元测试myMethodToTest
我想发送一个模拟对象来代替businessObject
。我使用 mockito 进行嘲笑,并使用 spy(new MyClass())
进行部分嘲笑,但在模拟呼叫以获得businessObject
时遇到麻烦。1. 是否可以模拟对业务对象的调用?如果是这样,怎么办?2. 如何在编写单元测试时重构此代码以帮助。任何指向此的资源都将有很大帮助。
谢谢!
要正确重构此代码,您需要:
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这样的框架使用依赖注入来做到这一点。值得您花时间。