繁体   English   中英

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

[英]Is there a simple way to inject dagger mocks in tests using FragmentScenario?

我刚刚遇到了FragmentScenario,并想用它来隔离地测试Fragments。 但是我的应用程序使用Dagger,我找不到一种运行FragmentScenario并将模拟字段放入待测片段的好方法。 我当前的测试设置将启动一个Activity,并使用DaggerMock来注入Mockito模拟依赖项。 但是我真的很想添加隔离的片段测试。

可以使用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类更加干净。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM