java - 测试第 3 方类的工厂

标签 java unit-testing guice mockito factory

我的应用程序使用第三方 jar(无法访问源等)我有一个工厂可以根据设置正确地创建一个对象(称之为 Foo),即

public FooFactoryImpl implements FooFactory {
    private final Settings settings;
    private final OtherDependency other;

    @Inject
    public FooFactoryImpl(Settings settings, OtherDependency other) {
        this.settings = settings;
        this.other = other;
    }

    public Foo create(String theirArg) {
        Foo newFoo = new Foo(theirArg); // there is no no-arg constructor

        // This isn't exactly the way I do it but this is shorter and close enough
        newFoo.setParamOne(settings.get("ParamOne")); 
        newFoo.setParamTwo(settings.get("ParamTwo"));
        // etc.
    }
}

我想使用 Mockito 对这个工厂进行单元测试——确保创建的对象配置正确。但当然,我遇到了 this problem ;也就是说,因为我的工厂调用 new,所以我无法注入(inject) spy 。

一种可能的解决方案是引入如下内容:

public FooFactoryDumb implements FooFactory {
    public Foo create(String theirArg) {
        return new Foo(theirArg);
    }
}

然后是这样的:

public FooFactoryImpl implements FooFactory {
    @Inject @Dumb private FooFactory inner;

    // snip, see above

    public create(String theirArg) {
        Foo newFoo = inner.create(theirArg);
        // etc.
    }
}

这似乎只是为了启用单元测试而编写的大量样板代码。它smells bad对我来说,但我可能是错的。有没有更好的办法?

最佳答案

有一种类似但更简单的方法:向您的工厂添加一个 protected 方法来创建一个 Foo:

protected Foo create(String theirArg){
    return new Foo(theirArg);
}

然后在你的工厂测试中,创建一个 Test Double你的 FactoryImpl 并覆盖创建方法:

private class FooFactoryImplTestDouble extends FooFactoryImpl{
    ...
    @Override
    protected Foo create(String theirArg){

        //create and return your spy here
    }
}

关于java - 测试第 3 方类的工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18405374/

相关文章:

java - Mockito 单元测试 - 错误放置或误用参数匹配器

unit-testing - 如何在带有 Jest 的 react-native 中使用模拟的 fetch() 对 API 调用进行单元测试

java - 与泛型的多重绑定(bind)

generics - Guice 和 Scala - 泛型依赖注入(inject)

java - 将类添加到子元素,并从具有相同父类的下一个容器开始

Java 对话框设置模态

java - 从数组和紧凑中删除索引

java - 用于 UTF-8 或 ISO-8859-1 编码 XML 的动态 SAX 解析器

c# - xunit-如何在单元测试中获取HttpContext.User.Identity

java - 验证 guice 模块配置 - 如何使用 SPI?