简体   繁体   English

如何测试包含void方法的Void方法?

[英]How to Test Void method which contains void method?

I am using PowerMockito. 我正在使用PowerMockito。 I would like to test the following code. 我想测试以下代码。

class Foo{
    void outerVoid(){
        innerVoid(); // method of another class
    }
}

How can I test OuterVoid() without invoking the innerVoid()? 如何在不调用innerVoid()的情况下测试OuterVoid()?

The innerVoid() contains database related objects so it should not be called, or it will become an integration test. innerVoid()包含与数据库相关的对象,因此不应调用它,否则它将成为集成测试。

Start by refactoring your code if possible. 如果可能,首先重构代码。

Create an interface Bar . 创建一个界面Bar

interface Bar {
    void innerVoid();
}

Now use the design pattern Dependency Injection to inject an implementation of this interface with the innerVoid() method into your Foo class. 现在,使用设计模式“ 依赖注入”将带有innerVoid()方法的此接口的实现注入到Foo类中。

class Foo {
    Bar bar;

    Bar getBar() {
        return this.bar;
    }

    void setBar(Bar bar) {
        this.bar = bar;
    }

    void outerVoid() {
        this.bar.innerVoid();
    }
}

Now you can mock the Bar class all you want. 现在,您可以随意模拟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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM