AndroidJUnitRunner
類別是一個 JUnit 測試執行器,可讓您在 Android 裝置上執行檢測 JUnit 4 測試,包括使用 Espresso、UI Automator 和 Compose 測試架構的應用程式。
測試執行器會負責將測試套件和應用程式載入裝置、執行測試及回報測試結果。
這個測試執行工具支援多項常見的測試工作,包括:
編寫 JUnit 測試
下列程式碼片段說明如何編寫檢測 JUnit 4 測試,驗證 ChangeTextBehavior
類別中的 changeText
作業是否正常運作:
Kotlin
@RunWith(AndroidJUnit4::class) // Only needed when mixing JUnit 3 and 4 tests @LargeTest // Optional runner annotation class ChangeTextBehaviorTest { val stringToBeTyped = "Espresso" // ActivityTestRule accesses context through the runner @get:Rule val activityRule = ActivityTestRule(MainActivity::class.java) @Test fun changeText_sameActivity() { // Type text and then press the button. onView(withId(R.id.editTextUserInput)) .perform(typeText(stringToBeTyped), closeSoftKeyboard()) onView(withId(R.id.changeTextBt)).perform(click()) // Check that the text was changed. onView(withId(R.id.textToBeChanged)) .check(matches(withText(stringToBeTyped))) } }
Java
@RunWith(AndroidJUnit4.class) // Only needed when mixing JUnit 3 and 4 tests @LargeTest // Optional runner annotation public class ChangeTextBehaviorTest { private static final String stringToBeTyped = "Espresso"; @Rule public ActivityTestRule<MainActivity>; activityRule = new ActivityTestRule<>;(MainActivity.class); @Test public void changeText_sameActivity() { // Type text and then press the button. onView(withId(R.id.editTextUserInput)) .perform(typeText(stringToBeTyped), closeSoftKeyboard()); onView(withId(R.id.changeTextBt)).perform(click()); // Check that the text was changed. onView(withId(R.id.textToBeChanged)) .check(matches(withText(stringToBeTyped))); } }
存取應用程式情境
使用 AndroidJUnitRunner
執行測試時,您可以呼叫靜態 ApplicationProvider.getApplicationContext()
方法,存取待測試應用程式的內容。如果您已經在應用程式中建立 Application
的自訂子類別,此方法會傳回自訂子類別的內容。
如果您是工具實作者,可使用 InstrumentationRegistry
類別存取低階測試 API。此類別包含 Instrumentation
物件、目標應用程式 Context
物件、測試應用程式 Context
物件,以及傳遞至測試的指令列引數。
篩選測試
在 JUnit 4.x 測試中,您可以使用註解來設定測試執行作業。這項功能可盡量減少在測試中加入樣板和條件式程式碼的需求。除了 JUnit 4 支援的標準註解外,測試執行器也支援 Android 專屬註解,包括:
@RequiresDevice
:指定測試應僅在實體裝置上執行,而非在模擬器上執行。@SdkSuppress
:禁止測試在低於指定級別的 Android API 級別上執行。舉例來說,如要停止執行低於 23 級別所有 API 級別的測試,請使用註解@SDKSuppress(minSdkVersion=23)
。@SmallTest
、@MediumTest
和@LargeTest
:分類測試的執行時間,因此決定執行測試的頻率。您可以使用此註解來篩選要執行的測試,設定android.testInstrumentationRunnerArguments.size
屬性:
-Pandroid.testInstrumentationRunnerArguments.size=small
資料分割測試
如果您需要平行執行測試,請共用多部伺服器以加快測試的執行速度,您可以將測試分成多個群組或「資料分割」。測試執行器支援將單一測試套件分割為多個資料分割,因此您可以輕鬆以群組的方式執行屬於相同資料分割的測試。每個資料分割都會透過索引號碼識別。執行測試時,請使用 -e numShards
選項指定要建立的個別資料分割數量,並使用 -e shardIndex
選項指定要執行的資料分割。
舉例來說,如要將測試套件分成 10 個資料分割,並且只執行第二個資料分割中的測試,請使用下列 adb 指令:
adb shell am instrument -w -e numShards 10 -e shardIndex 2
使用 Android Test Orchestrator
Android Test Orchestrator 可讓您在應用程式的 Instrumentation
叫用中執行每項測試。使用 AndroidJUnitRunner 1.0 以上版本時,您可以存取 Android Test Orchestrator。
Android Test Orchestrator 提供下列測試環境的優點:
- 最小共用狀態:每項測試都會在專屬的
Instrumentation
執行個體中執行。因此,如果測試共用應用程式狀態,則每次測試後,大部分共用狀態都會從裝置的 CPU 或記憶體中移除。每次測試後,如要從裝置的 CPU 和記憶體中移除「所有」共用狀態,請使用clearPackageData
標記。如需範例,請參閱「從 Gradle 啟用」一節。 - 隔離當機事件:即使有一個測試停止運作,也只會終止自己的
Instrumentation
執行個體。這表示套件中的其他測試仍在執行,提供了完整的測試結果。
由於 Android Test Orchestrator 會在每次測試完成後重新啟動應用程式,因此測試執行時間可能會增加。
Android Studio 和 Firebase Test Lab 已預先安裝 Android Test Orchestrator,但您需要在 Android Studio 中啟用該功能。
從 Gradle 啟用
如要使用 Gradle 指令列工具啟用 Android Test Orchestrator,請完成下列步驟:
- 步驟 1:修改 Gradle 檔案。在專案的
build.gradle
檔案中新增以下陳述式:
android {
defaultConfig {
...
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
// The following argument makes the Android Test Orchestrator run its
// "pm clear" command after each test invocation. This command ensures
// that the app's state is completely cleared between tests.
testInstrumentationRunnerArguments clearPackageData: 'true'
}
testOptions {
execution 'ANDROIDX_TEST_ORCHESTRATOR'
}
}
dependencies {
androidTestImplementation 'androidx.test:runner:1.1.0'
androidTestUtil 'androidx.test:orchestrator:1.1.0'
}
- 步驟 2:執行下列指令,執行 Android Test Orchestrator:
./gradlew connectedCheck
從 Android Studio 啟用
如要在 Android Studio 中啟用 Android Test Orchestrator,請將「透過 Gradle 啟用」顯示的陳述式新增至應用程式的 build.gradle
檔案。
從指令列啟用
如要透過指令列使用 Android Test Orchestrator,請在終端機視窗中執行下列指令:
DEVICE_API_LEVEL=$(adb shell getprop ro.build.version.sdk)
FORCE_QUERYABLE_OPTION=""
if [[ $DEVICE_API_LEVEL -ge 30 ]]; then
FORCE_QUERYABLE_OPTION="--force-queryable"
fi
# uninstall old versions
adb uninstall androidx.test.services
adb uninstall androidx.test.orchestrator
# Install the test orchestrator.
adb install $FORCE_QUERYABLE_OPTION -r path/to/m2repository/androidx/test/orchestrator/1.4.2/orchestrator-1.4.2.apk
# Install test services.
adb install $FORCE_QUERYABLE_OPTION -r path/to/m2repository/androidx/test/services/test-services/1.4.2/test-services-1.4.2.apk
# Replace "com.example.test" with the name of the package containing your tests.
# Add "-e clearPackageData true" to clear your app's data in between runs.
adb shell 'CLASSPATH=$(pm path androidx.test.services) app_process / \
androidx.test.services.shellexecutor.ShellMain am instrument -w -e \
targetInstrumentation com.example.test/androidx.test.runner.AndroidJUnitRunner \
androidx.test.orchestrator/.AndroidTestOrchestrator'
指令語法顯示,您可以安裝 Android Test Orchestrator,然後直接使用。
adb shell pm list instrumentation
使用不同工具鍊
如果您使用其他工具鍊測試應用程式,仍然可以完成下列步驟,以便使用 Android Test Orchestrator:
架構
Orchestrator 服務 APK 的儲存程序與測試 APK 和測試中的應用程式 APK 不同:

Android Test Orchestrator 會在測試套件執行時收集 JUnit 測試,但隨後會在自己的 Instrumentation
執行個體中,分別執行每項測試。
更多資訊
如要進一步瞭解如何使用 AndroidJUnitRunner,請參閱 API 參考資料。
其他資源
如要進一步瞭解如何使用 AndroidJUnitRunner
,請參閱下列資源。
範例
- AndroidJunitRunnerSample:展示測試註解、參數化測試,以及測試套件建立。