我有一个具有私有类变量初始化的类,
public class MyClass{
private BusinessObject businessObject = BusinessObjectGenerator.getBusinessObject();
public MyClass(){
}
public Object myMethodToTest(){
return businessObject.getObject();
}
}
现在,我正在尝试对
myMethodToTest
进行单元测试,我想发送一个模拟对象代替businessObject
。我使用嘲笑进行模仿,并使用spy(new MyClass())
进行部分嘲讽,但是在嘲笑获取businessObject
的调用时遇到了麻烦。1.是否可以模拟对businessObject的调用?如果可以,怎么办?
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的框架来执行此操作。这将是您值得的时间。