[英]How to Test Void method which contains void method?
我正在使用PowerMockito。 我想测试以下代码。
class Foo{
void outerVoid(){
innerVoid(); // method of another class
}
}
如何在不调用innerVoid()的情况下测试OuterVoid()?
innerVoid()包含与数据库相关的对象,因此不应调用它,否则它将成为集成测试。
如果可能,首先重构代码。
创建一个界面Bar
。
interface Bar {
void innerVoid();
}
现在,使用设计模式“ 依赖注入”将带有innerVoid()
方法的此接口的实现注入到Foo
类中。
class Foo {
Bar bar;
Bar getBar() {
return this.bar;
}
void setBar(Bar bar) {
this.bar = bar;
}
void outerVoid() {
this.bar.innerVoid();
}
}
现在,您可以随意模拟Bar
类。
Bar mockBar = createMockBar(...); // create a mock implementation of Bar
Foo foo = new Foo();
foo.setBar(mockBar);
... continue testing ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.