我在活动级别使用了类似场景的解决方案,请参阅How do you re-inject an android object, (Service, Activity...) being injected into by an AndroidInjector, into other objects? 以供参考。
我们如何应用此解决方案
考虑:
class MyFragment extends Fragment
{
....
}
创建一个子类:
class MyFragmentInjector extends MyFragment
{
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
initialiseDependencies();
super.onCreateView(inflater, container, savedInstanceState);
}
public void initialiseDependencies()
{
DaggerMyFragmentComponent.Factory.create().inject(this);
}
}
创建一个测试实现子类
class MyFragmentInjectorTestImpl extends MyFragment
{
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
initialiseDependencies();
super.onCreateView(inflater, container, savedInstanceState);
}
public void initialiseDependencies()
{
DaggerMyFragmentTestComponent.Factory.create().inject(this);
}
}
您的测试组件将包含所有模拟模块以替换您的真实模块:
这意味着要运行您的测试,您将拥有:
FragmentScenario.launch(MyFragmentInjectorTestImpl.class);
并使用
FragmentScenario.FragmentAction<MyFragmentInjectorTestImpl> mAction;
但由于 MyFragmentInjectorTestImpl 仍然是 MyFragment 的实例,因此您将使用注入的模拟依赖项来测试 MyFragment。
问题是所有这些初始化都必须在子类级别完成(因为它需要将依赖项注入其父级),这并不理想,如果您有很多片段,似乎有很多不必要的额外类实现,但这意味着带有真实代码的 MyFragment 类更干净。