Compose 可整合常見的測試架構。
與 Espresso 的互通性
在混合式應用程式中,您可以在檢視表階層中找到 Compose 元件,而在 Compose 元件組合 (透過 AndroidView
元件) 中找到檢視畫面。
這兩種類型不需要任何特殊步驟。您可以使用 Espresso 的 onView
比對檢視畫面,並使用 ComposeTestRule
比對 Compose 元素。
@Test
fun androidViewInteropTest() {
// Check the initial state of a TextView that depends on a Compose state.
Espresso.onView(withText("Hello Views")).check(matches(isDisplayed()))
// Click on the Compose button that changes the state.
composeTestRule.onNodeWithText("Click here").performClick()
// Check the new value.
Espresso.onView(withText("Hello Compose")).check(matches(isDisplayed()))
}
與 UiAutomator 的互通性
根據預設,可組合函式只能透過 UiAutomator 存取
便利的描述方式 (顯示文字、內容說明等)。如要存取任何使用 Modifier.testTag
的可組合項,則需為特定可組合項的子樹狀結構啟用語意屬性 testTagsAsResourceId
。如果可組合項沒有任何內容,就很適合啟用這項行為
其他專屬帳號代碼,例如可捲動的可組合函式 (例如 LazyColumn
)。
您只能在可組合項階層達到高時才能啟用語義屬性,以便確保所有設有 Modifier.testTag
的巢狀結構可組合項都可以從 UiAutomator 存取。
Scaffold(
// Enables for all composables in the hierarchy.
modifier = Modifier.semantics {
testTagsAsResourceId = true
}
){
// Modifier.testTag is accessible from UiAutomator for composables nested here.
LazyColumn(
modifier = Modifier.testTag("myLazyColumn")
){
// Content
}
}
任何設有 Modifier.testTag(tag)
的可組合項都可以藉由使用 By.res(resourceName)
並利用相同的 tag
做為 resourceName
的方式存取。
val device = UiDevice.getInstance(getInstrumentation())
val lazyColumn: UiObject2 = device.findObject(By.res("myLazyColumn"))
// Some interaction with the lazyColumn.
其他資源
- 在 Android 上測試應用程式:主要 Android 測試 到達網頁會針對測試的基礎知識和技巧提供廣泛的資訊。
- 測試基本知識:瞭解詳情 介紹測試 Android 應用程式的核心概念。
- 本機測試:您可以執行部分測試 或您自己的工作站
- 檢測設備測試:建議您也執行檢測設備測試。也就是直接在裝置上執行的測試。
- 持續整合:持續整合可讓您將測試整合至部署管道。
- 測試不同螢幕大小:由於使用者可使用的裝置種類繁多,因此您應測試各種螢幕大小。
- Espresso:適用於以檢視畫面為基礎的 UI、Espresso 知識仍對 Compose 的某些層面有所幫助 進行測試。