檢測設備測試套件

檢測設備測試套件會將裝置測試封裝到模組預設 src/androidTest/ 目錄外的獨立 testApk APK。您可以使用 Android Gradle 外掛程式 (AGP) 測試套件 DSL 進行設定,透過專屬依附元件、變化版本和指定裝置,區分 UI、整合或端對端檢查。

需求條件

如要使用檢測設備測試套件,請確認專案符合下列規定:

  • Android Studio Rabbit 3 Canary 3 以上版本
  • AGP 9.6.0-alpha03 以上版本
  • Gradle 9.7.1 以上版本和 JDK 17 以上版本
  • com.android.application 或 com.android.library 模組
  • 透過 Android Debug Bridge (ADB) 連線的裝置或模擬器,或建構管理裝置定義

如要進一步瞭解預先發布版比對,請參閱「與 Android Gradle 外掛程式預先發布版的相容性」。

設定檢測設備測試套件

如要將檢測設備測試套件新增至應用程式或程式庫模組,請完成下列步驟:

啟用測試套件

在專案的 gradle.properties 檔案中,啟用測試套件支援:

android.experimental.testSuiteSupport=true

設定套件

在模組的 build.gradle.kts 檔案中,使用 testApk 和 useJunitEngine 區塊以及 AgpTestSuiteInputParameters 列舉值,在 testOptions.customSuites 區塊內建立套件:

import com.android.build.api.dsl.AgpTestSuiteInputParameters

android {
    testOptions {
        // Optional: define build-managed virtual devices and device groups.
        managedDevices {
            localDevices {
                create("api34Atd") {
                    // Use a device profile from Android Studio.
                    device = "Pixel 6"
                    apiLevel = 34
                    systemImageSource = "aosp-atd"
                }
            }
            groups {
                create("ciPhones") {
                    targetDevices.add(allDevices.getByName("api34Atd"))
                }
            }
        }

        customSuites {
            create("androidSuite") {
                targetVariants += listOf("debug")

                testApk {
                    dependencies {
                        implementation("junit:junit:4.13.2")
                        implementation("androidx.test.ext:junit:1.2.1")
                        implementation("androidx.test:runner:1.6.2")
                    }
                }

                useJunitEngine {
                    includeEngines += listOf("android-test-engine")
                    // Match the engine and listener versions to your AGP
                    // version.
                    enginesDependencies.add(
                        "com.android.tools.androidtest:" +
                            "android-test-engine:9.6.0-alpha03"
                    )
                    enginesDependencies.add(
                        "com.android.tools.androidtest:" +
                            "android-test-engine-result-listener:9.6.0-alpha03"
                    )
                    enginesDependencies.add(
                        "org.junit.platform:junit-platform-launcher:1.10.2"
                    )

                    inputs += listOf(
                        // Omit TESTED_APKS in com.android.library modules.
                        AgpTestSuiteInputParameters.TESTED_APKS,
                        AgpTestSuiteInputParameters.TEST_APKS,
                        AgpTestSuiteInputParameters.ADB_EXECUTABLE,
                        AgpTestSuiteInputParameters.AAPT2_EXECUTABLE,
                    )
                }

                targets {
                    // Runs on connected adb devices.
                    create("default")
                    // Optional: runs on build-managed devices or groups in
                    // targetDevices.
                    create("managed") {
                        targetDevices += listOf("ciPhones")
                    }
                }
            }
        }
    }
}

AGP 會自動設定 AndroidJUnitRunner 測試執行器和套件 ID,不會沿用 androidTestImplementation 設定的依附元件。如要使用自訂執行器,請在 src/{suiteName}/AndroidManifest.xml 檔案中設定 instrumentation 元素的 android:name 屬性。

建立測試

將檢測設備測試放入 {module}/src/{suiteName}/kotlin/ 或 java/ 目錄,以及任何選用的 res/ 或 assets/ 目錄或 AndroidManifest.xml 檔案。例如,建立 app/src/androidSuite/kotlin/com/example/myapp/AppContextSuiteTest.kt 檔案:

package com.example.myapp

import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class AppContextSuiteTest {
    @Test
    fun useAppContext() {
        val appContext =
            InstrumentationRegistry.getInstrumentation().targetContext
        assertEquals("com.example.myapp", appContext.packageName)
    }
}

結合單元測試和檢測設備測試

如要在單一 Gradle 工作中執行本機 JVM 測試和檢測設備裝置測試,請在一個套件中同時宣告 hostJar 和 testApk 區塊。將主機測試放在 src/{suiteName}/test/ 目錄中,裝置測試則放在 src/{suiteName}/androidTest/ 目錄中:

import com.android.build.api.dsl.AgpTestSuiteInputParameters

android {
    testOptions {
        customSuites {
            create("combinedSuite") {
                targetVariants += listOf("debug")

                hostJar {
                    dependencies {
                        implementation(
                            "org.junit.jupiter:junit-jupiter-api:5.10.2"
                        )
                    }
                }

                testApk {
                    dependencies {
                        implementation("junit:junit:4.13.2")
                        implementation("androidx.test.ext:junit:1.2.1")
                        implementation("androidx.test:runner:1.6.2")
                    }
                }

                useJunitEngine {
                    includeEngines += listOf(
                        "junit-jupiter",
                        "android-test-engine",
                    )
                    enginesDependencies.add(
                        "org.junit.jupiter:junit-jupiter-engine:5.10.2"
                    )
                    enginesDependencies.add(
                        "com.android.tools.androidtest:" +
                            "android-test-engine:9.6.0-alpha03"
                    )
                    enginesDependencies.add(
                        "com.android.tools.androidtest:" +
                            "android-test-engine-result-listener:9.6.0-alpha03"
                    )
                    enginesDependencies.add(
                        "org.junit.platform:junit-platform-launcher:1.10.2"
                    )

                    inputs += listOf(
                        // Omit TESTED_APKS in com.android.library modules.
                        AgpTestSuiteInputParameters.TESTED_APKS,
                        AgpTestSuiteInputParameters.TEST_APKS,
                        AgpTestSuiteInputParameters.ADB_EXECUTABLE,
                        AgpTestSuiteInputParameters.AAPT2_EXECUTABLE,
                    )
                }

                targets {
                    create("default")
                }
            }
        }
    }
}

執行測試並收集涵蓋率

使用 Gradle 執行檢測套件、篩選測試案例,以及產生涵蓋率報表。

在已連結或建構管理的裝置上執行

在每個線上 ADB 裝置上執行連結的目標,或執行已設定 targetDevices 屬性的目標:

# Run on connected adb devices.
./gradlew :app:testDebugAndroidSuiteDefaultTestSuite
# Run on the ciPhones build-managed device group.
./gradlew :app:testDebugAndroidSuiteManagedCiPhonesTestSuite

篩選檢測設備測試

使用 Gradle 的 --tests 選項或 AndroidJUnitRunner 引數篩選測試:

./gradlew :app:testDebugAndroidSuiteDefaultTestSuite \
    --tests "com.example.myapp.AppContextSuiteTest.useAppContext"

您也可以使用 -Pandroid.testInstrumentationRunnerArguments.size=small 等專案屬性,在指令列上傳遞 AndroidJUnitRunner 引數。如要在 useJunitEngine 區塊中設定預設執行工具引數,請呼叫 addInputProperty 方法,例如 addInputProperty("android-test.instrumentation-args", "size=small")。

收集裝置端程式碼涵蓋率

裝置端程式碼涵蓋率需要可偵錯的版本,以及搭載 Android 9 (API 級別 28) 以上版本的裝置。如要收集檢測或混合套件的涵蓋率,請完成下列步驟:

  1. 在 gradle.properties 檔案中設定 android.experimental.androidTest.coverage.useOnDeviceAgent=true 屬性。
  2. 將套件的 codeCoverage 屬性設為 true。
  3. 如果連結多部裝置,請使用 ANDROID_SERIAL 環境變數指定一部裝置。

如要進一步瞭解代理程式需求,請參閱「查看程式碼涵蓋率報告 (使用裝置端代理程式)」。

檢查報表

測試執行完成後,AGP 會在下列路徑產生輸出內容:

  • HTML 測試報告:{module}/build/reports/tests/{taskName}/index.html
  • JUnit XML 結果:{module}/build/test-results/{taskName}/
  • 個別裝置的 XML 和 logcat: {module}/build/intermediates/{variant}/{taskName}/results/
  • 程式碼涵蓋率報表: {module}/build/reports/coverage/{suiteName}/index.html