【问题标题】:How to create Android UI Test for Android App Architecture ViewModels?如何为 Android App Architecture ViewModels 创建 Android UI 测试?
【发布时间】:2017-07-05 08:03:04
【问题描述】:

我一直在使用新的 Android 应用架构组件。测试文档留下了很多想象空间。我查看了android architecture components testing 文档的一部分,它的措辞非常模糊,如下所示。

用户界面和交互:这将是您唯一需要进行 Android UI Instrumentation 测试的时候。测试 UI 代码的最佳方法是创建 Espresso 测试。 您可以创建片段并为其提供模拟 ViewModel。 由于片段仅与 ViewModel 对话,因此模拟它足以完全测试此 UI

您如何通过将 ViewModel 的模拟传递给片段来编写 Espresso 测试?我还查看了 Google 提供的示例应用程序,它们也不是很有帮助。

假设这是我的示例片段类。

public class ExampleFragment extends LifecycleFragment {
    private ExampleViewModel mViewModel;
    @Inject ExampleViewModelFactory mViewModelFactory;

    public ExampleFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {        
        return inflater.inflate(R.layout.fragment_example, container, false);  
    }

    @Override
    public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ExampleComponent component = DaggerExampleComponent.builder().build();
    component.inject(this);
    mViewModel = ViewModelProviders.of(this, mViewModelFactory).get(ExampleViewModel.class);
    mViewModel.getExampleString().observe(this, exampleString -> {
       //Update UI
        });        
    }
}  

【问题讨论】:

    标签: android unit-testing android-fragments dagger-2 android-architecture-components


    【解决方案1】:

    关于提供模拟注入组件,AFAIK 有两种主要方法。 第一个是在google examples 中实现的,它提供了一个模拟视图模型实现作为不同的风格(例如在您的测试中)。

    另一个在“测试视图”部分中描述了in my blogpost here,其中 DaggerExampleComponent 由 Application 对象提供,并且您在 espresso 测试运行器中覆盖了应用程序对象,其中一个提供了假 ViewModel。

    Full working example here

    【讨论】:

      猜你喜欢
      • 2016-01-14
      • 2017-10-03
      • 2021-02-08
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多