作者:速度coinmer | 来源:互联网 | 2023-05-16 18:46
AsadvisedinDaggerdocumentation,forunittestingwedonthavetoinvolveDaggeratall,andfor
As advised in Dagger documentation, for unit testing we don't have to involve Dagger at all, and for the provided example it makes sense:
正如Dagger文档中所建议的那样,对于单元测试,我们根本不需要涉及Dagger,并且对于提供的示例,它是有意义的:
class ThingDoer {
private final ThingGetter getter;
private final ThingPutter putter;
@Inject ThingDoer(ThingGetter getter, ThingPutter putter) {
this.getter = getter;
this.putter = putter;
}
String doTheThing(int howManyTimes) { /* … */ }
}
With this class structure it is simple to unit test, just mock the getter
and putter
, pass them as constructor arguments, instruct mockito what to return when interacting with any of these objects, and then make assertions on doTheThing(...)
.
使用这种类结构,单元测试很简单,只需模拟getter和putter,将它们作为构造函数参数传递,指示mockito在与任何这些对象交互时返回什么,然后在doTheThing(...)上进行断言。
Where I am struggling at testing is when I have to unit test a class with a structure similar to this:
我在测试中苦苦挣扎的地方是我必须对类似于以下结构的类进行单元测试:
class ThingDoer {
@Inject
ThingGetter getter;
@Inject
ThingPutter putter;
@Inject
ThingMaker maker;
@Inject
// other 10 objects
public ThingDoer() {
App.getThingComponent().inject(this);
}
String doTheThing(int howManyTimes) { /* … */ }
}
As you can see, I am no longer using constructor injection, but field injection instead. The main reason is not have too many parameters in the constructor.
如您所见,我不再使用构造函数注入,而是使用场注入。主要原因是构造函数中没有太多参数。
Is there a way to inject mock dependencies in ThingDoer
when all its dependencies are provided using field injections?
当使用字段注入提供所有依赖项时,有没有办法在ThingDoer中注入模拟依赖项?
1 个解决方案