Android Gradle 外掛程式中的測試套件

Android Gradle 外掛程式 (AGP) 可讓您在模組的 testOptions 區塊中,將測試整理成已命名的測試套件。每個套件都會定義自己的來源集、依附元件、JUnit 平台測試引擎和目標建構變化版本。

使用測試套件的好處

根據預設,Android 模組會提供一個用於本機單元測試的 test 來源集,以及一個用於檢測設備測試的 androidTest 來源集。測試套件會將測試組織與這兩個來源集分離,以便您執行下列操作:

  • 依用途區分測試:將單元、Robolectric、UI、螢幕截圖和備份測試,分別放在專屬的 src/{suiteName}/ 目錄中,不要混在 src/test/ 或 src/androidTest/ 目錄。
  • 隔離依附元件和引擎:設定每個套件的類別路徑和 JUnit 平台測試引擎,不需在應用程式或 testImplementation 和 androidTestImplementation 設定中新增依附元件。
  • 指定特定變化版本和裝置:為每個套件選取建構變化版本和裝置,以便在本機執行快速檢查,並在持續整合中執行較長的套件。

套件類型

AGP 包含適用於特殊工作流程的內建測試套件,以及適用於自訂套件的 AgpTestSuite 介面。下表列出可用的套件類型:

套件類型 DSL 容器 目的
單元測試套件 testOptions.customSuites 使用 hostJar 區塊在本機 JVM 上執行 JUnit 5、JUnit 4 或 Robolectric 測試。
檢測設備測試套件 testOptions.customSuites 使用 testApk 區塊和 android-test-engine 測試引擎,在已連結或由建構系統管理的裝置上執行裝置測試。
使用測試套件進行螢幕截圖測試 testOptions.screenshotTests 在主機上算繪並比較 @PreviewTest 個 Compose 預覽畫面。
自動備份與還原測試 testOptions.backupTests 驗證本機、雲端和裝置對裝置轉移的應用程式資料。
Android Studio 的歷程功能 testOptions.customSuites 在連結裝置上執行 AI 驅動的 XML 使用者歷程。
自訂資產或混合套件 testOptions.customSuites 使用自訂引擎執行靜態測試定義,或將 hostJar、testApk 和 assets 區塊合併至單一套件。

需求條件

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

  • Android Studio Rabbit 3 Canary 3 以上版本
  • AGP 9.6.0-alpha03 以上版本
  • Gradle 9.7.1 以上版本和 JDK 17 以上版本
  • com.android.application 或 com.android.library 模組

com.android.kotlin.multiplatform.library 或 com.android.test 模組不支援測試套件。如要進一步瞭解預先發布版比對,請參閱「與 Android Gradle 外掛程式預先發布版的相容性」。

設定自訂測試套件

如需逐步設定指南,請參閱「單元測試套件」和「檢測設備測試套件」。如要定義自訂套件,請先在專案的 gradle.properties 檔案中啟用測試套件:

android.experimental.testSuiteSupport=true

接著,在模組 build.gradle.kts 檔案的 testOptions.customSuites 區塊中宣告套件。指定 targetVariants 屬性、一或多個來源區塊、useJunitEngine 區塊,以及 targets 區塊中的至少一個目標:

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

android {
    testOptions {
        customSuites {
            create("mySuite") {
                // Exact variant names to test, such as "debug" or "demoDebug".
                targetVariants += listOf("debug")

                // Add one or more blocks: hostJar {}, testApk {}, or assets {}.
                assets {}

                useJunitEngine {
                    includeEngines += listOf("my-custom-engine")
                    enginesDependencies.add(
                        "com.example:my-custom-junit-engine:1.0.0"
                    )
                    enginesDependencies.add(
                        "org.junit.platform:junit-platform-launcher:1.10.2"
                    )

                    // Request build and SDK artifacts read by your engine.
                    inputs += listOf(
                        AgpTestSuiteInputParameters.STATIC_FILES,
                        // Omit TESTED_APKS in com.android.library modules.
                        AgpTestSuiteInputParameters.TESTED_APKS,
                        AgpTestSuiteInputParameters.ADB_EXECUTABLE,
                    )
                }

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

在自訂 TestEngine 實作中,使用 TestSuiteExecutionClient.default 屬性讀取 AgpTestSuiteInputParameters 列舉值和標準 TestEngineInputProperty 常數,例如 SERIAL_IDS 和 RESULTS_DIR。

來源集目錄

每個套件的目錄版面配置取決於其宣告一個來源區塊,還是合併多個來源區塊。下表列出 {module}/src/{suiteName}/ 目錄下的預設路徑:

來源區塊 單一來源套件 混合套件
hostJar kotlin/、java/、resources/ test/kotlin/、test/java/、test/resources/
testApk kotlin/、java/、res/、assets/、AndroidManifest.xml androidTest/kotlin/、androidTest/java/、androidTest/res/、androidTest/assets/、androidTest/AndroidManifest.xml
assets 套件根目錄 assetsTest/

請勿重複使用內建來源集、變種版本、建構類型或變化版本名稱 (例如 main、androidTest 或 debug) 做為套件名稱。

每個變化版本的控制組目標

如要啟用或停用特定變體的套件目標,請透過 beforeVariants 區塊中的 HasTestSuitesBuilder.suites 屬性設定 TestSuiteTargetBuilder 介面:

androidComponents {
    beforeVariants { variantBuilder ->
        if (variantBuilder.buildType == "release") {
            variantBuilder.suites["mySuite"]
                ?.targets
                ?.get("default")
                ?.enable = false
        }
    }
}

執行套件並檢查報表

AGP 會為每個變化版本、套件和目標組合建立 Gradle 工作。下表列出工作模式:

任務類型 命名模式 範例指令
標準套件目標 test{Variant}{SuiteName}{Target}TestSuite ./gradlew :app:testDebugMySuiteDefaultTestSuite
使用 targetDevices 屬性指定目標 test{Variant}{SuiteName}{Target}{Devices}TestSuite ./gradlew :app:testDebugAndroidSuiteManagedCiPhonesTestSuite
基準更新 (requiresUpdateTask = true) update{Variant}{SuiteName}{Target}TestSuite ./gradlew :app:updateDebugScreenshotTestDefaultTestSuite
模組報表匯總 testAllSuites ./gradlew :app:testAllSuites
模組和依附元件匯總 testAllSuitesWithDependencies ./gradlew :app:testAllSuitesWithDependencies

除非您使用 withTestTaskProviders 方法連結 test、connectedCheck 和 check 工作,否則這些工作不會執行自訂套件。如要啟用 testAllSuites 和 testAllSuitesWithDependencies 工作,請在 gradle.properties 檔案中設定 android.experimental.reportAggregationSupport=true 屬性。

每次執行套件時,系統都會將輸出內容寫入下列位置:

  • HTML 測試報告:{module}/build/reports/tests/{taskName}/index.html
  • JUnit XML 結果:{module}/build/test-results/{taskName}/
  • 程式碼涵蓋率報表: {module}/build/reports/coverage/{suiteName}/index.html
  • 匯總報表: {module}/build/reports/{aggregationTask}/test-report/index.html和 coverage-report/index.html

如要產生程式碼涵蓋率報表,請將套件的 codeCoverage 屬性設為 true。如果是 Compose 螢幕截圖套件,請在 build.gradle.kts 檔案中使用 testOptions.customSuites.named("{suiteName}") { codeCoverage = true } 設定套件。

已知問題和限制

測試套件有下列限制:

  • IDE 整合:Android Studio 不支援自訂測試套件。即使建構設定正確,程式碼編輯器仍可能在套件來源檔案中顯示未解析的參照錯誤。請改用 Gradle,透過指令列建構及執行測試套件。
  • 工作快取:測試套件工作一律會在叫用時重新執行,不會從 Gradle 建構快取載入。系統會略過沒有測試檔案的套件,並顯示 NO-SOURCE 狀態。