1

我一直在使用新的 Android 应用架构组件。测试文档留下了很多想象空间。我查看了android architecture components testing part of the documentation,它非常含糊,如下所述。

用户界面和交互:这将是您唯一需要进行 Android UI Instrumentation 测试的时候。测试 UI 代码的最佳方法是创建 Espresso 测试。您可以创建片段并为其提供模拟 ViewModel。由于 Fragment 仅与 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
        });        
    }
}  
4

1 回答 1

1

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

另一个在我的博客文章中的“测试视图”部分中进行了描述,其中 DaggerExampleComponent 由 Application 对象提供,并且您在 espresso 测试运行器中覆盖应用程序对象,该运行程序提供了一个提供假 ViewModel 的对象。

完整的工作示例在这里

于 2017-07-05T08:48:18.637 回答