我的应用程序使用第三方 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 对这个工厂进行单元测试——确保创建的对象配置正确。但是,当然,我遇到了这个问题;也就是说,因为我的工厂调用new
,我不能注入间谍。
一种可能的解决方案是引入如下内容:
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.
}
}
这似乎是很多样板代码,只是为了启用单元测试。我闻起来很臭,但我可能错了。有没有更好的办法?