本指南將說明如何使用 SDK 管理員安裝 Espresso,以及如何使用 Gradle 建構 Espresso。建議使用 Android Studio。
設定測試環境
為避免發生問題,強烈建議您關閉系統動畫 用於測試的虛擬或實體裝置在您的裝置上,位於 設定 >開發人員選項,請停用下列 3 項設定:
- 視窗動畫比例
- 轉場動畫比例
- 動畫影片長度比例
新增 Espresso 依附元件
如要在專案中新增 Espresso 依附元件,請完成下列步驟:
- 開啟應用程式的
build.gradle
檔案。這通常不是頂層build.gradle
檔案,而是app/build.gradle
。 - 在依附元件中加入下列程式碼:
Groovy
androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' androidTestImplementation 'androidx.test:runner:1.6.1' androidTestImplementation 'androidx.test:rules:1.6.1'
Kotlin
androidTestImplementation('androidx.test.espresso:espresso-core:3.6.1') androidTestImplementation('androidx.test:runner:1.6.1') androidTestImplementation('androidx.test:rules:1.6.1')
設定檢測執行程式
在同一個 build.gradle
檔案的 android.defaultConfig
中新增下列行:
Groovy
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
Kotlin
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
Gradle 建構檔案範例
Groovy
plugins { id 'com.android.application' } android { compileSdkVersion 33 defaultConfig { applicationId "com.my.awesome.app" minSdkVersion 21 targetSdkVersion 33 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } } dependencies { androidTestImplementation 'androidx.test:runner:1.6.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' }
Kotlin
plugins { id("com.android.application") } android { compileSdkVersion(33) defaultConfig { applicationId = "com.my.awesome.app" minSdkVersion(21) targetSdkVersion(33) versionCode = 1 versionName = "1.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } } dependencies { androidTestImplementation('androidx.test:runner:1.6.1') androidTestImplementation('androidx.test.espresso:espresso-core:3.6.1') }
分析
為了確保每個新版本的進度都符合預期, 執行器收集分析具體來說,它會上傳 套件的雜湊值 每個叫用中測試的應用程式名稱。這可讓我們評估使用 Espresso 的不重複套件數量,以及使用量。
如果您不想上傳這類資料,可以在檢測指令中加入 disableAnalytics
引數,選擇不採用這項機制:
adb shell am instrument -e disableAnalytics true
新增第一個測試
Android Studio 預設會在 src/androidTest/java/com.example.package/
中建立測試。
使用規則的 JUnit4 測試範例:
Kotlin
@RunWith(AndroidJUnit4::class) @LargeTest class HelloWorldEspressoTest { @get:Rule val activityRule = ActivityScenarioRule(MainActivity::class.java) @Test fun listGoesOverTheFold() { onView(withText("Hello world!")).check(matches(isDisplayed())) } }
Java
@RunWith(AndroidJUnit4.class) @LargeTest public class HelloWorldEspressoTest { @Rule public ActivityScenarioRule<MainActivity> activityRule = new ActivityScenarioRule<>(MainActivity.class); @Test public void listGoesOverTheFold() { onView(withText("Hello world!")).check(matches(isDisplayed())); } }
執行測試
您可以在 Android Studio 或指令列中執行測試。
在 Android Studio 中
如要在 Android Studio 中建立測試設定,請完成下列步驟:
- 依序開啟「Run」(執行) >編輯設定。
- 新增 Android 測試設定。
- 選擇模組。
- 新增特定的檢測執行器:
androidx.test.runner.AndroidJUnitRunner
- 執行新建的設定。
使用指令列
執行下列 Gradle 指令:
./gradlew connectedAndroidTest