我刚刚遇到了FragmentScenario,并且希望使用它来隔离地测试片段。但是我的应用程序使用了Dagger,我找不到一种好的方法来运行FragmentScenario,并将模拟字段放入正在测试的片段中。我当前的测试设置启动一个活动,并使用DaggerMock注入mockito模拟依赖项。不过,我真的很想添加孤立的片段测试。
用FragmentScenario可以做到这一点吗?很快就会得到支持吗?
我看过这篇文章提出了一种解决方案,但我不喜欢只为测试https://proandroiddev.com/testing-dagger-fragments-with-fragmentscenario-155b6ad18747而打开片段类的想法
发布于 2019-07-13 16:44:08
我在活动级别使用了类似的解决方案,请参阅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类与实际代码相比要干净一些。
https://stackoverflow.com/questions/56943606
复制相似问题