Android tests are based on JUnit, and you can run them either as local unit tests on the JVM or as instrumented tests on an Android device. This page provides an introduction to the concepts and tools for building Android tests.

// Android的测试基于JUnit

Test Types


When using Android Studio to write any of your tests, your test code must go into one of two different code directories (source sets). For each module in your project, Android Studio includes both source sets, corresponding to the following test types:

//对于每一个项目的模块,Androidstudio都会包含这两个类型的source sets

Local unit tests
Located at module-name/src/test/java/.

These tests run on the local JVM and do not have access to functional Android framework APIs.

// 这些测试运行在本地JAVA虚拟机上,不会访问Android框架层的api

To get started, see Building Local Unit Tests.

Instrumented tests
Located at module-name/src/androidTest/java/.

These are all tests that must run on an Android hardware device or an Android emulator.

//这些测试必须运行在Android硬件设备上或者模拟器上

Instrumented tests are built into an APK that runs on the device alongside your app under test. The system runs your test APK and your app under tests in the same process, so your tests can invoke methods and modify fields in the app, and automate user interaction with your app.

//instruments test构建了一个apk和你的app一起安装,系统会让你的app和测试apk一同运行在同一个进程,这样你的测试可以调用应用中的方法并且 可以修改变量,让和应用的交互变得自动化

For information about how to create instrumented tests, see the following topics:

However, the local unit tests and instrumented tests described above are just terms that help distinguish the tests that run on your local JVM from the tests that run on the Android platform (on a hardware device or emulator). The real testing types that you should understand when building a complete test suite are described in the following table.

//然而上面描述的local unit test and instrumentes test只是帮助区分他们一个是运行在本地虚拟机,一个是运行在Android平台上。真正的测试类型的分类应该是如下表描述的:

Type Subtype Description
Unit tests
Local Unit Tests Unit tests that run locally on the Java Virtual Machine (JVM). Use these tests to minimize execution time when your tests have no Android framework dependencies or when you can mock the Android framework dependencies.
Instrumented unit tests Unit tests that run on an Android device or emulator. These tests have access to Instrumentationinformation, such as the Context of the app you are testing. Use these tests when your tests have Android dependencies that mock objects cannot satisfy.
Integration Tests
Components within your app only This type of test verifies that the target app behaves as expected when a user performs a specific action or enters a specific input in its activities. For example, it allows you to check that the target app returns the correct UI output in response to user interactions in the app’s activities. UI testing frameworks like Espressoallow you to programmatically simulate user actions and test complex intra-app user interactions.
Cross-app Components This type of test verifies the correct behavior of interactions between different user apps or between user apps and system apps. For example, you might want to test that your app behaves correctly when the user performs an action in the Android Settings menu. UI testing frameworks that support cross-app interactions, such as UI Automator, allow you to create tests for such scenarios.

Test APIs


The following are common APIs used for testing apps on Android.

JUnit

You should write your unit or integration test class as a JUnit 4 test class. The framework offers a convenient way to perform common setup, teardown, and assertion operations in your test.

A basic JUnit 4 test class is a Java class that contains one or more test methods. A test method begins with the @Test annotation and contains the code to exercise and verify a single functionality (that is, a logical unit) in the component that you want to test.

The following snippet shows an example JUnit 4 integration test that uses the Espresso APIs to perform a click action on a UI element, then checks to see if an expected string is displayed.

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityInstrumentationTest {     @Rule
    public ActivityTestRule mActivityRule = new ActivityTestRule<>(
            MainActivity.class);     @Test
    public void sayHello(){
        onView(withText("Say hello!")).perform(click());         onView(withId(R.id.textView)).check(matches(withText("Hello, World!")));
    }
}

In your JUnit 4 test class, you can call out sections in your test code for special processing by using the following annotations:

//你可以通过下面的注解唤起一些代码段用户特殊的处理

  • @Before: Use this annotation to specify a block of code that contains test setup operations. The test class invokes this code block before each test. You can have multiple @Before methods but the order in which the test class calls these methods is not guaranteed.                   // 用before注解来指定包含test代码构建操作的代码块。测试类调用这个代码块在所有测试代码之前,你可以有多个before声明的代码块,但是他们的相对运行顺序是没法保证的
  • @After: This annotation specifies a block of code that contains test tear-down operations. The test class calls this code block after every test method. You can define multiple @After operations in your test code. Use this annotation to release any resources from memory          // after注解指定了包含有测试类的拆除工作的代码块。测试类调用这个代码在所有测试方法之后,你可以定义多个after注解代码块。使用这个注解来释放内存中的资源
  • @Test: Use this annotation to mark a test method. A single test class can contain multiple test methods, each prefixed with this annotation.    //使用test注解来标记测试方法,一个测试类可以包含多个测试方法,每一个方法都带有test前缀
  • @Rule: Rules allow you to flexibly add or redefine the behavior of each test method in a reusable way. In Android testing, use this annotation together with one of the test rule classes that the Android Testing Support Library provides, such as ActivityTestRule or ServiceTestRule.   //rule允许你灵活添加和冲定义每一个测试方法的行为以便重用。在Android 测试中,会以它和其他的测试规则类一起使用,例如ActivityTestRule or ServiceTestRule.
  • @BeforeClass: Use this annotation to specify static methods for each test class to invoke only once. This testing step is useful for expensive operations such as connecting to a database. //使用这个注解来指定一个对于每一个测试类只会调用一次的静态方法,这个测试搭建方法对于开销较大的操作例如连接数据库等是非常有帮助的。
  • @AfterClass: Use this annotation to specify static methods for the test class to invoke only after all tests in the class have run. This testing step is useful for releasing any resources allocated in the @BeforeClass block.
  • @Test(timeout=): Some annotations support the ability to pass in elements for which you can set values. For example, you can specify a timeout period for the test. If the test starts but does not complete within the given timeout period, it automatically fails. You must specify the timeout period in milliseconds, for example: @Test(timeout=5000).   //一些注释支持添加可以设置值的元素的功能,例如你可以指定一个超市时间对于这个测试。如果测试开始但是没有在超时时间内完成,他会自动失败,超时时间以毫秒指定

For more annotations, see the documentation for JUnit annotations and the Android annotations.

Use the JUnit Assert class to verify the correctness of an object's state. The assert methods compare values you expect from a test to the actual results and throw an exception if the comparison fails. Assertion classes describes these methods in more detail.

Android Testing Support Library

The Android Testing Support Library provides a set of APIs that allow you to quickly build and run test code for your apps, including JUnit 4 and functional UI tests. The library includes the following instrumentation-based APIs that are useful when you want to automate your tests:

AndroidJUnitRunnerA JUnit 4-compatible test runner for Android.EspressoA UI testing framework; suitable for functional UI testing within an app.UI AutomatorA UI testing framework suitable for cross-app functional UI testing between both system and installed apps.

Assertion classes

Because Android Testing Support Library APIs extend JUnit, you can use assertion methods to display the results of tests. An assertion method compares an actual value returned by a test to an expected value, and throws an AssertionException if the comparison test fails. Using assertions is more convenient than logging, and provides better test performance.

To simplify test development, you should use the Hamcrest library, which lets you create more flexible tests using the Hamcrest matcher APIs.

Monkey and monkeyrunner

The Android SDK includes two tools for functional-level app testing:

Monkey
This is a command-line tool that sends pseudo-random streams of keystrokes, touches, and gestures to a device. You run it with the Android Debug Bridge (adb) tool, and use it to stress-test your app, report back errors any that are encountered, or repeat a stream of events by running the tool multiple times with the same random number seed.
monkeyrunner
This tool is an API and execution environment for test programs written in Python. The API includes functions for connecting to a device, installing and uninstalling packages, taking screenshots, comparing two images, and running a test package against an app. Using the API, you can write a wide range of large, powerful, and complex tests. You run programs that use the API with the monkeyrunner command-line tool.

Guides for Building Android Tests


The following documents provide more detail about how to build and run a variety of test types:

Building Local Unit Tests
Build unit tests that have no dependencies or only simple dependencies that you can mock, which run on your local JVM.
Building Instrumented Unit Tests
Build complex unit tests with Android dependencies that cannot be satisfied with mock objects, which run on a hardware device or emulator.
Automating User Interface Tests
Create tests to verify that the user interface behaves correctly for user interactions within a single app or for interactions across multiple apps.
Testing App Compontent Integrations
Verify the behavior of components that users do not directly interact with, such as a service or a content provider.
Testing Display Performance
Write tests that measure your app's UI performance to ensure a consistently smooth user experience.
 

Getting Started with Testing ——开始单元测试的更多相关文章

  1. VS2010(2012)中使用Unit Testing进行单元测试

    原文 VS2010(2012)中使用Unit Testing进行单元测试 使用VS 2012自带的Unit Testing工具进行单元测试是非常方便的.网上关于这方面的例子很多,这篇随笔只起个人学习笔 ...

  2. [Go语言学习]之一:搭建单元测试环境

    最近开始正式的学习Go语言,奉行我学习一项新技术的步骤和原则( 笔记 + 单元测试 + demo ).首先学习了开发环境的配置,并立即搭建了单元测试的环境,这样可以一边写笔记,一边进行测试和学习,从而 ...

  3. 使用MSTest进行单元测试

    我之前写过一篇XUNit的简介:使用Xunit来进行单元测试.Xunit在当时确实是一个最简单易用的测试框架,然而,随着发展,Xunit也变得复杂了不少,光写一个最简单的测试就要导入8个包. 如果在大 ...

  4. golang单元测试

    使用testing进行单元测试 golang的测试库testing 测试文件与被测试文件在同一个包中 测试文件名为被测试文件名(去后缀)_test.go 测试用例函数以Test开头,TestFunc1 ...

  5. 自动化测试之 seleniumIDE,Selenium1,selenium2和testNG入门

    由于前期三个月公司的项目一直在改需求阶段,一直是手动测试,现在项目雏形以及基本页面功能都确定下来,为了不让自己陷入天天测同一功能的无限循环中,故开始自动化测试的学习之路,也为自己以后的发展铺铺路. 一 ...

  6. Activiti-03-query api

    Query API 有两种方式从引擎中查询数据, 查询 API 和本地查询. API方式:   List<Task> tasks = taskService.createTaskQuery ...

  7. 从壹开始前后端分离 [ Vue2.0+.NET Core2.1] 二十一║Vue实战:开发环境搭建【详细版】

    缘起 哈喽大家好,兜兜转转终于来到了Vue实战环节,前边的 6 篇关于Vue基础文章我刚刚简单看了看,感觉写的还是不行呀,不是很系统,所以大家可能看上去比较累,还是得抽时间去润润色,修改修改语句和样式 ...

  8. jenkins自动化工具使用教程

    自动化构建.测试.部署.代码检测越来越重要.主要有一下几点原因 1.  企业做大,项目变多,多端支持(web,h5,小程序等) 2.  微服务提倡高内聚低耦合,项目因拆分变多 3.  DevOps自动 ...

  9. jenkins自动化工具使用教程(转)

    自动化构建.测试.部署.代码检测越来越重要.主要有一下几点原因 企业做大,项目变多,多端支持(web,h5,小程序等) 微服务提倡高内聚低耦合,项目因拆分变多 DevOps自动化运维流行 集群化,高可 ...

随机推荐

  1. King's Quest

    poj1904:http://poj.org/problem?id=1904 题意:国王有n个儿子,现在这n个儿子要在n个女孩里选择自己喜欢的,有的儿子可能喜欢多个,最后国王的向导给出他一个匹配,匹配 ...

  2. Js 表单序列化

    http://www.w3cmm.com/javascript/serialize-form.html

  3. Myeclipse中可以正常显示,但运行后的网页找不到图片

    目录为: 1 douban   1.1 css   1.2 image 2 pages   2.1 index.jsp 路径为:<img  src="../douya/image/lg ...

  4. HashMap循环遍历方式及其性能对比

    主要介绍HashMap的四种循环遍历方式,各种方式的性能测试对比,根据HashMap的源码实现分析性能结果,总结结论.   1. Map的四种遍历方式 下面只是简单介绍各种遍历示例(以HashMap为 ...

  5. C#中的四舍五入算法

    最近在产品开发过程中遇到一个问题,就是在对数值进行截取,例如说保留两位小数时,最终得到的结果跟预期的在某些情况下会产生差异,这个差异的表现就是最后一位与预期的不一致,也就是说在"四舍五入&q ...

  6. STL之algorithm、numeric、functional

    <algorithm>是所有STL头文件中最大的一个,其中常用到的功能范围涉及到比较.交换.查找.遍历操作.复制.修改.反转.排序.合并等等. <numeric>体积很小,只包 ...

  7. 前端开发者应当了解的 Web 缓存知识

    缓存优点 通常所说的Web缓存指的是可以自动保存常见http请求副本的http设备.对于前端开发者来说,浏览器充当了重要角色.除此外常见的还有各种各样的代理服务器也可以做缓存.当Web请求到达缓存时, ...

  8. Struts2配置文件讲解

    解决在断网环境下,配置文件无提示的问题我们可以看到Struts.xml在断网的情况下,前面有一个叹号,这时,我们按alt+/ 没有提示,这是因为” http://struts.apache.org/d ...

  9. javascript从入门到精通(二)

    第二章.数据结构 JavaScript脚本语言的数据结构包括:标识符.关键字.常量.变量等. 标识符:就是一个名称.在JavaScript用来命名变量和函数或者用作JavaScript代码中某些循环的 ...

  10. LeetCode201 Bitwise AND of Numbers Range Java 题解

    题目: Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all num ...