聲明:本系列文章是對 Android Testing Support Library官方文檔的翻譯,水平有限,歡迎批評指正。
1. Espresso 概覽
2. Espresso 設(shè)置說明
3. Espresso 基礎(chǔ)
4. Espresso 備忘錄
5. Espresso 意圖
6. Espresso 高級示例
7. Espresso Web
8. AndroidJUnitRunner
9. ATSL 中的 JUnit4 規(guī)則
10. UI Automator
11. 可訪問性檢查
本指南涵蓋了使用 SDK Manager 安裝 Espresso 和使用 Gradle 構(gòu)建 Espresso 測試兩部分內(nèi)容。推薦使用 Android Studio。
配置測試環(huán)境
為了避免花屏,我們強烈建議在虛擬機或真實設(shè)備上測試時關(guān)閉系統(tǒng)動畫。
- 在設(shè)備上的設(shè)置->開發(fā)者選項中禁用一下三項設(shè)置:
窗口動畫縮放
過渡動畫縮放
動畫程序時長縮放
下載 Espresso
- 確保你已經(jīng)安裝了最新的 Extras 下的 Android Support Repository (查看使用說明)
- 打開應(yīng)用的
build.gradle文件。這通常不是頂級build.gradle,而是app/build.gradle。 - 在 dependencies 節(jié)點下添加以下行:
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile 'com.android.support.test:runner:0.5'
- 參考下載小節(jié)查看更多的工件(espresso-contrib, espresso-web 等)
設(shè)置 instrumentation runner
- 在
?android.defaultConfig? 下添加下面的代碼:
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
build.gradle 示例文件
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22"
defaultConfig {
applicationId "com.my.awesome.app"
minSdkVersion 10
targetSdkVersion 22.0.1
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
dependencies {
// App's dependencies, including test
compile 'com.android.support:support-annotations:22.2.0'
// Testing-only dependencies
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
}
分析數(shù)據(jù)
為了確保每一個新發(fā)布的版本正常工作,test runner 會收集分析數(shù)據(jù)。具體而言,每次調(diào)用它都會上傳待測應(yīng)用包名的一個 hash 值。這可以使我們在 Espresso 特性包的數(shù)量以及它的體積之間做出權(quán)衡。
如果你不希望上傳此類數(shù)據(jù),可以通過給 test runner 傳入 ?disableAnalytics “true”? 來禁止(參考 如何傳入自定義參數(shù))
添加第一個測試
Android Studio 默認(rèn)在 ?src/androidTest/java/com.example.package/? 中創(chuàng)建測試。
使用 Rules 創(chuàng)建的 JUnit4 測試實例:
@RunWith(AndroidJUnit4.class)
@LargeTest
public class HelloWorldEspressoTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule(MainActivity.class);
@Test
public void listGoesOverTheFold() {
onView(withText("Hello world!")).check(matches(isDisplayed()));
}
}
執(zhí)行測試
使用 Android Studio 執(zhí)行
創(chuàng)建測試配置
在 Android Studio中:
- 打開菜單 Run -> Edit Configurations
- 添加一個新的 Android Tests 配置
- 選擇 module
- 添加一個指定的 instrumentation runner:
android.support.test.runner.AndroidJUnitRunner
執(zhí)行這個新創(chuàng)建的配置
在命令行中通過 Gradle 執(zhí)行
執(zhí)行 ?./gradlew connectedAndroidTest