我的应用程序使用第三方 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/