正如 Ali Derbane 同我写的第一篇文章有关于Android功能测试中提到的,有许多的框架供你使用,在这个旅程的第二部份我将给你介绍一个叫做Espresso 的功能测试框架。
简介
Espresso是在2013的GTAC上首次被提出来的,目的是让开发能够写出简洁,美观以及可靠的UI测试,Espresso由以下几个组件构成:
- “Espresso”类提供类”onView”以及”onData”方法,可用于特定接口上的最优数
- ViewMatchers
包含了一个实现 Mathcer <? super View>
接口的对象集合,通过使用该类你可以收集以及验证View 元素,例如,获取一个文本内容为“7“的View 元素(Button)
- ViewActions
包含了在View上执行动作的ViewAction对象的集合。这些动作都是通过ViewInteraction.perform
方法进行执行的,并且它可能包含了多个动作,例如在View元素(Button)进行点击操作
- ViewAssertions
是ViewAssertion
的集合,用于对Views的检查。
举个例子说明以下,这些测试组件就像下面这样:
Espresso.onView(ViewMatchers.withText("7")).perform(ViewActions.click());
Espresso.onView(withId(R.id.result)).check(ViewAssertions.matches(ViewMatchers.withText("42")));
一个好消息,去年Google提出的一个 Testing Support Library 目前已经包含了Espresso。所以让我们开始使用Espresso吧
举个例子,我们将通过写一些测试用例对Android calculator application 再次进行测试。先实现一个测试是否6x7=42的普通测试场景
定义test runner
为了能够使用Espresso,我们首先必须先定义好谁来运行我们的测试用例,Espreeso 使用了一个叫AndroidJunitRunner的新的测试运行器,这个运行器是基于InstrumentationTestRunner和GoogleInstrumentationTestRunner ,运行JUnit3和JUnit4来测试你的Android应用程序。
首先在你的build.gradle中添加依赖项,这里已经默认你已经安装了Testing Support Library.
dependencies {
androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
}
再来在你的build.gradle 中的android.defaultConfig中添加运行器。
defaultConfig {
...
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
编写测试用例
你可能已经想到了,测试类必须在src\androidTest\com.example.package.tests中.包com.example.package是在AndroidManifest文件中指定的属性.
每一个测试类都必须继承ActivityInstrumentationTestCase2这个抽象类,并且默认使用测试的Activity作为范型。
它还需要通过super()方法传递给父类.要使被测试的Activity被测试框架调用,只需要在setup方法中同步调用getActivity()方法.
public class FunctionalInstrumentationTest extends ActivityInstrumentationTestCase2<ActivityToTest> {
public FunctionalInstrumentationTest() {
super(ActivityToTest.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
getActivity();
}
}
正如刚才提到的,我们要验证是否6x7=42
public void testAnswer_to_the_Ultimate_Question_of_Life_the_Universe_and_Everything() {
onView(withText("7")).perform(click());
onView(withText("×")).perform(click());
onView(withText("6")).perform(click());
onView(withText("=")).perform(click());
onView(withId(R.id.resText)).check(matches(withText("42")));
}
你可能注意到了,这个例子使用了静态的导入,这样子的做法是为了能让代码更具有可读性。
你可能要用到一些其他动作:
- pressBack()
; 模拟按下“back“按钮
- isDisplayed()
; 检查元素是否是显示的
- scrollTo
; 滑动到一个元素
运行测试用例
现在让我们开始有趣的部分吧,让我们开始执行测试,这个可以通过命令行命令gradle connectedAndroidTest
或者使用Android Studio:
1. 打开菜单|编辑配置
2. 增加一个新的Android 测试配置
3. 选择一个你要测试的模块
4. 定义你的测试运行器:android.support.test.runner.AndroidJUnitRunner