我正在使用 PowerMockito。我想测试以下代码。
class Foo{
void outerVoid(){
innerVoid(); // method of another class
}
}
如何在不调用 innerVoid() 的情况下测试 OuterVoid()?
innerVoid() 包含与数据库相关的对象,因此不应调用它,否则它将成为集成测试。
最佳答案
如果可能的话,首先重构您的代码。
创建界面Bar
。
interface Bar {
void innerVoid();
}
现在使用设计模式Dependency Injection使用 innerVoid()
方法将此接口(interface)的实现注入(inject)到您的 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 ...
关于java - 如何测试包含void方法的Void方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16838227/