Compose 與通用測試架構整合。
與 Espresso 的互通性
在混合式應用程式中,您可以在檢視區塊階層和 Compose 可組合項 (透過 AndroidView
可組合項) 中找到 Compose 元件。
這兩種類型不需要任何特殊步驟。您可以使用 Espresso 的 onView
比對檢視畫面,並將 Compose 元素與 ComposeTestRule
比對。
@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)
並使用與 resourceName
相同的 tag
來存取。
val device = UiDevice.getInstance(getInstrumentation())
val lazyColumn: UiObject2 = device.findObject(By.res("myLazyColumn"))
// Some interaction with the lazyColumn.
其他資源
- 在 Android 上測試應用程式:主要 Android 測試到達網頁提供了更全面的測試基礎知識和技巧。
- 測試基礎知識:進一步瞭解測試 Android 應用程式的核心概念。
- 本機測試:您可以在自己的工作站本機執行部分測試。
- 檢測設備測試:建議您也執行檢測設備測試。也就是說,直接在裝置上執行的測試。
- 持續整合:持續整合可讓您將測試整合至部署管道。
- 測試不同的螢幕大小:有許多裝置可供使用者使用,建議您針對不同螢幕大小進行測試。
- Espresso:雖然適用於以 View 為基礎的 UI,但 Espresso 知識在 Compose 測試的某些方面仍非常實用。