Espresso在Android-Studio中进行单元测试
在这篇文章中,我们将学习如何在Android Studio中配置工程用于测试,在开发机器上编写并运行单元测试,以及如何在手机上做功能UI测试。包括:
更新包含JUnit和Android Testing Support Library的Gradle构建文件
编写运行在本机Java虚拟机上的单元测试
编写运行在手机或者虚拟机上的Espresso测试
原文链接:http://www.jianshu.com/p/03118c11c199
1.你需要什么
Android Studio v1.2+
Android 4.0+的测试设备
2.创建新的Android Studio工程
如果是第一次启动Android Studio,从欢迎页选择“Start a new Android Studio project”。如果已经打开了一个工程,选择File>New>New Project…
“Create new project”向导会指导整个过程,在第一页输入如下内容:
| Setting | Value |
| ——: | :——-: |
|Application Name | TestingExample |
|Company demain| testing.example.com|
这样会保证你的代码同codelab讲解的内容具有一致的命名。其他的选项都设置为默认,一路点击Next直到工程创建完毕。
点击Run按钮检查app是否运行正常,要么从模拟器列表中选择一个启动,要么确认开启了debug模式的设备通过USB同电脑正确连接。
app目前没有做任何事情,但是屏幕上应该显示“Hello world!”和app的名字。
3.配置支持单元测试的工程
在写测试之前,让我们做下简单的检查,确保工程配置正确。
打开工程的build.gradle(Module:app)文件,添加JUnit4依赖,点击Gradle sync按钮。
1 | `build.gradle |
Calculator.java package com.example.testing.testingexample; public class Calculator { public double sum(double a, double b){ return 0; } public double substract(double a, double b){ return 0; } public double divide(double a, double b){ return 0; } public double multiply(double a, double b){ return 0; } }
1 |
|
Calculator.java package com.example.testing.testingexample; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class CalculatorTest { private Calculator mCalculator; @Before public void setUp() throws Exception { mCalculator = new Calculator(); } @Test public void testSum() throws Exception { //expected: 6, sum of 1 and 5 assertEquals(6d, mCalculator.sum(1d, 5d), 0); } @Test public void testSubstract() throws Exception { assertEquals(1d, mCalculator.substract(5d, 4d), 0); } @Test public void testDivide() throws Exception { assertEquals(4d, mCalculator.divide(20d, 5d), 0); } @Test public void testMultiply() throws Exception { assertEquals(10d, mCalculator.multiply(2d, 5d), 0); } }
1 |
|
./gradlew test
1 |
|
public double sum(double a, double b){ return a + b; }
1 |
|
build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "22.0.1" defaultConfig { applicationId "com.example.testing.testingexample" minSdkVersion 15 targetSdkVersion 22 versionCode 1 versionName "1.0" //ADD THIS LINE: testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } //ADD THESE LINES: packagingOptions { exclude 'LICENSE.txt' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.0.0' //← MAKE SURE IT’S 22.0.0 testCompile 'junit:junit:4.12' //ADD THESE LINES: androidTestCompile 'com.android.support.test:runner:0.2' androidTestCompile 'com.android.support.test:rules:0.2' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.1' }
1 | 另外,Android Studio可能会提醒你Build Tools 22.0.1没有安装。你应该接受修复建议,Studio会为你安装Build Tools或者在build.gradle中把这行修改成已经安装在你电脑的版本。 |
activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:hint="Enter your name here" android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textView"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Say hello!" android:layout_below="@+id/editText" android:onClick="sayHello"/>
1 | 还需要在MainActivity.java中添加onClick handler: |
MainActivity.java public void sayHello(View v){ TextView textView = (TextView) findViewById(R.id.textView); EditText editText = (EditText) findViewById(R.id.editText); textView.setText("Hello, " + editText.getText().toString() + "!"); }
1 |
|
** MainActivityInstrumentationTest.java package com.example.testing.testingexample; import android.support.test.InstrumentationRegistry; import android.support.test.espresso.action.ViewActions; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.LargeTest; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; @RunWith(AndroidJUnit4.class) @LargeTest public class MainActivityInstrumentationTest { private static final String STRING_TO_BE_TYPED = "Peter"; @Rule public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>( MainActivity.class); @Test public void sayHello(){ onView(withId(R.id.editText)).perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard()); //line 1 onView(withText("Say hello!")).perform(click()); //line 2 String expectedText = "Hello, " + STRING_TO_BE_TYPED + "!"; onView(withId(R.id.textView)).check(matches(withText(expectedText))); //line 3 } }
- 1.首先,找到ID为editText的view,输入Peter,然后关闭键盘;
- 2.接下来,点击Say hello!的View,我们没有在布局的XML中为这个Button设置id,因此,通过搜索它上面的文字来找到它;
- 3.最后,将TextView上的文本同预期结果对比,如果一致则测试通过;
你也可以右键点击域名运行测试,选择Run>MainActivityInstrume…(第二个带Android图标的)
这样就会在模拟器或者连接的设备上运行测试,你可以在手机屏幕上看到被执行的动作(比如在EditText上打字)。最后会在Android Studio输出通过和失败的测试结果。
测试源码请看[TestingExample](https://github.com/foolingdutchman/TestingExample)