UI Automator 測試架構提供一組 API,可用於建構與使用者應用程式和系統應用程式互動的 UI 測試。
現代 UI Automator 測試簡介
UI Automator 2.4 推出精簡、適合 Kotlin 的領域特定語言 (DSL),可簡化 Android UI 測試的編寫作業。這個新的 API 介面著重於以述詞為基礎的元素尋找,以及對應用程式狀態的明確控制。您可以使用這項功能,建立更易於維護且可靠的自動化測試。
UI Automator 可讓您從應用程式程序外部測試應用程式。這樣一來,您就能測試已套用壓縮功能的發布版本。UI Automator 也有助於編寫 Macrobenchmark 測試。
現代化方法的主要特色包括:
- 專屬的
uiAutomator測試範圍,可讓測試程式碼更簡潔、更具表現力。 onElement、onElements和onElementOrNull等方法,用於尋找具有明確述詞的 UI 元素。- 條件式元素的內建等待機制
onElement*(timeoutMs: Long = 10000) - 明確的應用程式狀態管理,例如
waitForStable和waitForAppToBeVisible。 - 直接與無障礙視窗節點互動,進行多視窗模式測試。
- 內建螢幕截圖功能和
ResultsReporter,可用於視覺測試和偵錯。
設定專案
如要開始使用新版 UI Automator API,請更新專案的 build.gradle.kts 檔案,加入最新依附元件:
Kotlin
dependencies {
...
androidTestImplementation("androidx.test.uiautomator:uiautomator:2.4.0-alpha05")
}
Groovy
dependencies {
...
androidTestImplementation "androidx.test.uiautomator:uiautomator:2.4.0-alpha05"
}
核心 API 概念
以下各節說明新版 UI Automator API 的核心概念。
uiAutomator 測試範圍
在 uiAutomator { ... } 區塊中存取所有新的 UI Automator API。這個函式會建立 UiAutomatorTestScope,為測試作業提供簡潔且類型安全的環境。
uiAutomator { // All your UI Automator actions go here. startApp("com.example.targetapp") onElement { textAsString() == "Hello, World!" }.click() }
尋找 UI 元素
使用 UI Automator API 搭配述詞,找出 UI 元素。這些述詞可讓您定義文字、選取或聚焦狀態,以及內容說明等屬性的條件。
onElement { predicate }:在預設逾時時間內,傳回符合述詞的第一個 UI 元素。如果找不到相符的元素,函式會擲回例外狀況。// Find a button with the text "Submit" and click it. onElement { textAsString() == "Submit" }.click() // Find a UI element by its resource ID. onElement { viewIdResourceName == "my_button_id" }.click() // Allow a permission request. watchFor(PermissionDialog) { clickAllow() }
onElementOrNull { predicate }:與onElement類似,但如果函式在逾時時間內找不到相符元素,則會傳回null。也不會擲回例外狀況。請對選用元素使用這個方法。val optionalButton = onElementOrNull { textAsString() == "Skip" } optionalButton?.click() // Click only if the button exists.
onElements { predicate }:等待至少一個 UI 元素符合指定述詞,然後傳回所有相符 UI 元素的清單。// Get all items in a list Ui element. val listItems = onElements { className == "android.widget.TextView" && isClickable } listItems.forEach { it.click() }
以下是使用 onElement 呼叫的幾個訣竅:
鏈結
onElement呼叫巢狀元素:您可以鏈結onElement呼叫,按照父項與子項階層結構,在其他元素中尋找元素。// Find a parent Ui element with ID "first", then its child with ID "second", // then its grandchild with ID "third", and click it. onElement { viewIdResourceName == "first" } .onElement { viewIdResourceName == "second" } .onElement { viewIdResourceName == "third" } .click()
傳遞代表毫秒的值,為
onElement*函式指定逾時時間。// Find a Ui element with a zero timeout (instant check). onElement(0) { viewIdResourceName == "something" }.click() // Find a Ui element with a custom timeout of 10 seconds. onElement(10_000) { textAsString() == "Long loading text" }.click()
與 UI 元素互動
模擬點擊或在可編輯欄位中設定文字,與 UI 元素互動。
// Click a Ui element. onElement { textAsString() == "Tap Me" }.click() // Set text in an editable field. onElement { className == "android.widget.EditText" }.setText("My input text") // Perform a long click. onElement { contentDescription == "Context Menu" }.longClick()
處理應用程式狀態和監控器
管理應用程式的生命週期,並處理測試期間可能出現的非預期 UI 元素。
應用程式生命週期管理
API 提供多種方法,可控制受測應用程式的狀態:
// Start a specific app by package name. Used for benchmarking and other // self-instrumenting tests. startApp("com.example.targetapp") // Start a specific activity within the target app. startActivity(SomeActivity::class.java) // Start an intent. startActivityIntent(myIntent) // Clear the app's data (resets it to a fresh state). clearAppData()
處理非預期的 UI
您可以使用 watchFor API 定義處理常式,處理測試流程中可能出現的非預期 UI 元素,例如權限對話方塊。這會使用內部監控機制,但提供更多彈性。
// import androidx.test.uiautomator.PermissionDialog @Test fun myTestWithPermissionHandling() = uiAutomator { startActivity(MainActivity::class.java) // Register a watcher to click "Allow" if a permission dialog appears. watchFor(PermissionDialog) { clickAllow() } // Your test steps that might trigger a permission dialog. onElement { textAsString() == "Request Permissions" }.click() // Example: You can register a different watcher later if needed. clearAppData() // Now deny permissions. startApp("com.example.targetapp") watchFor(PermissionDialog) { clickDeny() } onElement { textAsString() == "Request Permissions" }.click() }
PermissionDialog 是 ScopedWatcher<T> 的範例,其中 T 是做為範圍傳遞至 watchFor 中區塊的物件。您可以根據這個模式建立自訂監控程式。
等待應用程式顯示設定和穩定性
有時測試需要等待元素顯示或穩定。UI Automator 提供多個 API,可協助您完成這項作業。
waitForAppToBeVisible("com.example.targetapp") 會等待具有指定套件名稱的 UI 元素在可自訂的逾時時間內顯示在畫面上。
// Wait for the app to be visible after launching it. startApp("com.example.targetapp") waitForAppToBeVisible("com.example.targetapp")
waitForStable() API 確認 UI 處於穩定狀態。
// Wait for the entire active window to become stable. device.activeWindow().waitForStable() // Wait for a specific Ui element to become stable (e.g., after a loading animation). onElement { viewIdResourceName == "my_loading_indicator" }.waitForStable()
使用 UI Automator 執行 Macrobenchmark 和基準設定檔
使用 UI Automator 搭配 Jetpack Macrobenchmark 進行效能測試,並產生基準設定檔,因為這項工具提供可靠的方法,可與應用程式互動,並從使用者角度評估效能。
Macrobenchmark 會使用 UI Automator API 驅動 UI 並評估互動。舉例來說,在啟動基準測試中,您可以使用 onElement 偵測 UI 內容何時完全載入,以便測量完整顯示時間 (TTFD)。在卡頓基準測試中,UI Automator API 可用於捲動清單或執行動畫,以測量影格時間。startActivity() 或 startIntent() 等函式,有助於在開始測量前,讓應用程式進入正確狀態。
產生基準設定檔時,系統會自動執行應用程式的關鍵使用者歷程 (CUJ),記錄哪些類別和方法需要預先編譯。UI Automator 是編寫這類自動化指令碼的理想工具。與其他方法相比,現代 DSL 的述詞元素尋找和內建等待機制 (onElement) 可讓測試執行更穩定、更具確定性。這種穩定性可減少不穩定情形,並確保產生的基準設定檔能準確反映在最重要的使用者流程中執行的程式碼路徑。
進階功能
下列功能適用於較複雜的測試情境。
與多個視窗互動
UI Automator API 可讓您直接與 UI 元素互動及檢查。這項功能特別適用於涉及多個視窗的情境,例如子母畫面 (PiP) 模式或分割畫面版面配置。
// Find the first window that is in Picture-in-Picture mode. val pipWindow = windows() .first { it.isInPictureInPictureMode == true } // Now you can interact with elements within that specific window. pipWindow.onElement { textAsString() == "Play" }.click()
螢幕截圖和視覺斷言
直接在測試中擷取整個畫面、特定視窗或個別 UI 元素的螢幕截圖。這對視覺迴歸測試和偵錯很有幫助。
uiAutomator { // Take a screenshot of the entire active window. val fullScreenBitmap: Bitmap = device.activeWindow().takeScreenshot() fullScreenBitmap.saveToFile(File("/sdcard/Download/full_screen.png")) // Take a screenshot of a specific UI element (e.g., a button). val buttonBitmap: Bitmap = onElement { viewIdResourceName == "my_button" }.takeScreenshot() buttonBitmap.saveToFile(File("/sdcard/Download/my_button_screenshot.png")) // Example: Take a screenshot of a PiP window. val pipWindowScreenshot = windows() .first { it.isInPictureInPictureMode == true } .takeScreenshot() pipWindowScreenshot.saveToFile(File("/sdcard/Download/pip_screenshot.png")) }
Bitmap 的 saveToFile 擴充功能函式可簡化將擷取圖片儲存至指定路徑的程序。
使用 ResultsReporter 偵錯
ResultsReporter 可協助您在 Android Studio 中,將螢幕截圖等測試構件直接與測試結果建立關聯,方便檢查及偵錯。
uiAutomator { startApp("com.example.targetapp") val reporter = ResultsReporter("MyTestArtifacts") // Name for this set of results. val file = reporter.addNewFile( filename = "my_screenshot", title = "Accessible button image" // Title that appears in Android Studio test results. ) // Take a screenshot of an element and save it using the reporter. onElement { textAsString() == "Accessible button" } .takeScreenshot() .saveToFile(file) // Report the artifacts to instrumentation, making them visible in Android Studio. reporter.reportToInstrumentation() }
從舊版 UI Automator 遷移
如果您現有的 UI Automator 測試是以舊版 API 介面編寫,請參考下表,瞭解如何改用新版做法:
| 動作類型 | 舊版 UI Automator 方法 | 新的 UI Automator 方法 |
|---|---|---|
| 進入點 | UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) |
將測試邏輯納入 uiAutomator { ... } 範圍。 |
| 尋找 UI 元素 | device.findObject(By.res("com.example.app:id/my_button")) |
onElement { viewIdResourceName == "my\_button" } |
| 尋找 UI 元素 | device.findObject(By.text("Click Me")) |
onElement { textAsString() == "Click Me" } |
| 等待閒置 UI | device.waitForIdle() |
建議使用 onElement 的內建逾時機制,否則請使用 activeWindow().waitForStable() |
| 尋找子元素 | 手動巢狀 findObject 呼叫 |
onElement().onElement() 鏈結 |
| 處理權限對話方塊 | UiAutomator.registerWatcher() |
watchFor(PermissionDialog) |