有没有一种简单的方法可以在使用 FragmentScenario 的测试中注入匕首模拟?



我刚刚遇到了FragmentScenario,并希望用它来单独测试Fragments。但是我的应用程序使用dagger,我找不到运行 FragmentScenario 并将模拟字段放入受测片段的好方法。我当前的测试设置启动了一个活动,并使用 DaggerMock 注入模拟依赖项。但是,我真的很想添加孤立的片段测试。

是否可以使用FragmentScenario执行此操作?它会很快得到支持吗?

我已经看到这篇文章提出了一个解决方案,但我不喜欢必须打开片段类只是为了测试 https://proandroiddev.com/testing-dagger-fragments-with-fragmentscenario-155b6ad18747 的想法

我在活动级别为类似场景使用了解决方案,请参阅如何将由 AndroidInjector 注入的 android 对象(服务、活动...)重新注入到其他对象中? 供参考。

我们如何应用此解决方案

考虑:

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 类与你的真实代码有点干净。

最新更新