【问题标题】:Is there a simple way to inject dagger mocks in tests using FragmentScenario?有没有一种简单的方法可以在使用 FragmentScenario 的测试中注入 dagger mocks?
【发布时间】:2019-07-08 23:20:50
【问题描述】:

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

是否可以使用 FragmentScenario 做到这一点?会很快得到支持吗?

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

【问题讨论】:

    标签: android android-fragments mockito android-espresso dagger


    【解决方案1】:

    我在活动级别使用了类似场景的解决方案,请参阅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 类更干净。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2019-04-29
      • 1970-01-01
      • 2011-06-16
      相关资源
      最近更新 更多