Compose 整合了常見的測試架構。
與 Espresso 的互通性
在混合式應用程式中,您可以在檢視區塊階層中找到 Compose 元件,並在 Compose 可組合項中 (透過 AndroidView
可組合項) 找到檢視畫面。
這兩種類型不需要任何特殊步驟。您會比對檢視畫面與 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 測試的某些方面。