Android 单元测试的最佳实践?

Best practices for Android Unit Testing?

我正在开发移动 android 应用程序。 Android 单元测试最常用的 libraries/frameworks 是什么?感觉大部分的业务逻辑,数据库测试,Web服务测试都可以用JUnit来完成。

但是,测试 UI、UI 工作流程等的最佳方法是什么?例如,我们如何测试 Android 应用程序是否成功启动网络浏览器?或者我们如何确认按钮,某些东西是否被成功按下?或者图片是否加载成功?

Android 开发者网站上有一个 guide for automated user interface testing。我没试过,但它看起来像你一直在寻找的东西。

我使用 JUnit for unit testing and Robolectric 进行仪器测试。

This article 向您展示了一个带有 Robolectric

的 Hello World 示例

最近,我一直在研究使用 Arquillian Droidium 在 Android 中进行集成测试。

如果您想测试一些使用 REST API 的代码,您可以使用 WireMock 模拟它。使用此库,您可以通过代码模拟 REST APIs,甚至可以在您自己的机器上部署模拟 HTTP 服务器并设置您自己的模拟映射。

对于 REST API 模拟,我也建议您使用 Mockable.io

2017年答案

Android 文档有一个名为 Best Practices for Testing 的主题系列。我将从那里开始。

当您开始一个新项目时,默认情况下会设置本地单元测试和插桩测试。给出的一般建议是尽可能使用本地单元测试。有时这需要模拟一个使用 Android API 的对象。 documentation recommends using Mockito in these cases. When UI tests (instrumented tests) need to be done, Android provides the Espresso framework. There are also other tools available, like the Exerciser Monkey (for stress testing) and UI Automator(用于测试多个应用交互)。

例子

See this answer 如何开始在 Android Studio 中进行测试。