測試 Compose 版面配置
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
測試應用程式的 UI,確認撰寫程式碼的行為是否正確。這有助於及早發現錯誤,並提升應用程式品質。
Compose 提供一組測試 API,可找出元素、驗證其屬性,以及執行使用者動作。API 也包含時間管理等進階功能。使用這些 API 建立穩健的測試,驗證應用程式的行為。
View
如果您使用檢視區塊而非 Compose,請參閱「在 Android 上測試應用程式」一節。
特別是「自動執行 UI 測試」指南,是很好的起點。本文將說明如何自動執行裝置端測試,包括使用檢視區塊時。
核心概念
以下是測試 Compose 程式碼的幾個重要概念:
- 語意:語意會指定 UI 的意義,讓測試與特定元素互動。
- 測試 API:測試 API 可用於找出元素、驗證其屬性,以及執行使用者動作。
- 同步處理:同步處理會驗證測試是否等待 UI 閒置,再執行動作或進行判斷。
- 互通性:互通性可讓測試在同一個應用程式中,同時使用 Compose 和以 View 為基礎的元素。
測試一覽表
如要瞭解 Compose 測試的所有重要主題,請參閱測試一覽表。
設定
設定應用程式,以便測試 Compose 程式碼。
首先,請將下列依附元件新增至包含 UI 測試的模組的 build.gradle
檔案:
// Test rules and transitive dependencies:
androidTestImplementation("androidx.compose.ui:ui-test-junit4:$compose_version")
// Needed for createComposeRule(), but not for createAndroidComposeRule<YourActivity>():
debugImplementation("androidx.compose.ui:ui-test-manifest:$compose_version")
這個模組包含 ComposeTestRule
和名為 AndroidComposeTestRule
的 Android 實作透過這項規則,您可以設定撰寫內容或存取活動。您可以使用工廠函式建構規則,包括 createComposeRule
,或在需要存取活動時使用 createAndroidComposeRule
。Compose 的一般 UI 測試如下所示:
// file: app/src/androidTest/java/com/package/MyComposeTest.kt
class MyComposeTest {
@get:Rule val composeTestRule = createComposeRule()
// use createAndroidComposeRule<YourActivity>() if you need access to
// an activity
@Test
fun myTest() {
// Start the app
composeTestRule.setContent {
MyAppTheme {
MainScreen(uiState = fakeUiState, /*...*/)
}
}
composeTestRule.onNodeWithText("Continue").performClick()
composeTestRule.onNodeWithText("Welcome").assertIsDisplayed()
}
}
其他資源
- 在 Android 上測試應用程式:這個主要的 Android 測試到達網頁,提供更廣泛的測試基礎知識和技術。
- 測試基礎知識:進一步瞭解測試 Android 應用程式背後的概念。
- 本機測試:您可以在自己的工作站上,在本機執行部分測試。
- 檢測設備測試:建議您也執行檢測設備測試。也就是直接在裝置上執行的測試。
- 持續整合:
持續整合可讓您將測試整合至部署管道。
- 測試不同螢幕大小:使用者可選擇的裝置種類繁多,因此您應測試不同螢幕大小。
- Espresso:雖然 Espresso 是專為以 View 為基礎的 UI 設計,但您仍可運用相關知識,進行部分 Compose 測試。
程式碼實驗室
詳情請參閱 Jetpack Compose 測試程式碼研究室。
範例
為您推薦
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-08-21 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-08-21 (世界標準時間)。"],[],[],null,["# Test your Compose layout\n\nTest your app's UI to verify that behavior of your Compose code is\ncorrect. This lets you catch errors early and improve the quality of your app.\n\nCompose provides a set of testing APIs to find elements, verify their\nattributes, and perform user actions. The APIs also include advanced features\nsuch as time manipulation. Use these APIs to create robust tests that verify\nyour app's behavior.\n| **Important:** For more on testing Android apps in general, including testing `View` elements, see the [general testing section](/training/testing). A good place to start is the [Fundamentals of testing Android apps](/training/testing/fundamentals) guide.\n\nViews\n-----\n\nIf you are working with views instead of Compose, see the general [Test apps on\nAndroid](/training/testing) section.\n\nIn particular, a good place to start is the [Automate UI tests](/training/testing/ui-tests) guide. It\nlays out how you can automate tests that run on-device, including when using\nviews.\n\nKey Concepts\n------------\n\nThe following are some key concepts for testing your Compose code:\n\n- **[Semantics](/develop/ui/compose/testing/semantics)**: Semantics give meaning to your UI, allowing tests to interact with specific elements.\n- **[Testing APIs](/develop/ui/compose/testing/apis)**: Testing APIs let you find elements, verify their attributes, and perform user actions.\n- **[Synchronization](/develop/ui/compose/testing/synchronization)**: Synchronization verifies that tests wait for the UI to be idle before performing actions or making assertions.\n- **[Interoperability](/develop/ui/compose/testing/interoperability)**: Interoperability enables tests to work with both Compose and View-based elements in the same app.\n\nTesting cheatsheet\n------------------\n\nSee the [testing cheatsheet](/develop/ui/compose/testing/testing-cheatsheet) for an overview of all the key topics you should\nlearn about testing in Compose.\n\nSetup\n-----\n\nSet up your app to let you test compose code.\n\nFirst, add the following dependencies to the `build.gradle` file of the module\ncontaining your UI tests: \n\n // Test rules and transitive dependencies:\n androidTestImplementation(\"androidx.compose.ui:ui-test-junit4:$compose_version\")\n // Needed for createComposeRule(), but not for createAndroidComposeRule\u003cYourActivity\u003e():\n debugImplementation(\"androidx.compose.ui:ui-test-manifest:$compose_version\")\n\nThis module includes a [`ComposeTestRule`](/reference/kotlin/androidx/compose/ui/test/junit4/ComposeTestRule) and an implementation for Android\ncalled [`AndroidComposeTestRule`](/reference/kotlin/androidx/compose/ui/test/junit4/AndroidComposeTestRule). Through this rule you can set Compose\ncontent or access the activity. You construct the rules using factory functions,\neither [`createComposeRule`](/reference/kotlin/androidx/compose/ui/test/junit4/package-summary#createComposeRule()) or, if you need access to an activity,\n[`createAndroidComposeRule`](/reference/kotlin/androidx/compose/ui/test/junit4/package-summary#createAndroidComposeRule()). A typical UI test for Compose looks like this: \n\n // file: app/src/androidTest/java/com/package/MyComposeTest.kt\n\n class MyComposeTest {\n\n @get:Rule val composeTestRule = createComposeRule()\n // use createAndroidComposeRule\u003cYourActivity\u003e() if you need access to\n // an activity\n\n @Test\n fun myTest() {\n // Start the app\n composeTestRule.setContent {\n MyAppTheme {\n MainScreen(uiState = fakeUiState, /*...*/)\n }\n }\n\n composeTestRule.onNodeWithText(\"Continue\").performClick()\n\n composeTestRule.onNodeWithText(\"Welcome\").assertIsDisplayed()\n }\n }\n\nAdditional Resources\n--------------------\n\n- **[Test apps on Android](/training/testing)**: The main Android testing landing page provides a broader view of testing fundamentals and techniques.\n- **[Fundamentals of testing](/training/testing/fundamentals):** Learn more about the core concepts behind testing an Android app.\n- **[Local tests](/training/testing/local-tests):** You can run some tests locally, on your own workstation.\n- **[Instrumented tests](/training/testing/instrumented-tests):** It is good practice to also run instrumented tests. That is, tests that run directly on-device.\n- **[Continuous integration](/training/testing/continuous-integration):** Continuous integration lets you integrate your tests into your deployment pipeline.\n- **[Test different screen sizes](/training/testing/different-screens):** With some many devices available to users, you should test for different screen sizes.\n- **[Espresso](/training/testing/espresso)**: While intended for View-based UIs, Espresso knowledge can still be helpful for some aspects of Compose testing.\n\nCodelab\n-------\n\nTo learn more, try the [Jetpack Compose Testing codelab](/codelabs/jetpack-compose-testing).\n\n### Samples\n\nRecommended for you\n-------------------\n\n- Note: link text is displayed when JavaScript is off\n- [Semantics in Compose](/develop/ui/compose/semantics)\n- [Window insets in Compose](/develop/ui/compose/layouts/insets)\n- [Other considerations](/develop/ui/compose/migrate/other-considerations)"]]