测试 Compose 布局
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
测试应用的界面,以验证 Compose 代码的行为是否正确。这样一来,您就可以尽早发现错误并提高应用质量。
Compose 提供了一组测试 API,用于查找元素、验证其属性以及执行用户操作。这些 API 还包括时间控制等高级功能。使用这些 API 可创建可靠的测试来验证应用的行为。
View
如果您使用的是视图而不是 Compose,请参阅常规的在 Android 上测试应用部分。
具体来说,您可以先参阅自动化界面测试指南。其中介绍了如何自动执行在设备上运行的测试,包括使用视图时。
关键概念
以下是测试 Compose 代码的一些关键概念:
- 语义:语义为界面赋予意义,使测试能够与特定元素互动。
- 测试 API:借助测试 API,您可以查找元素、验证其属性以及执行用户操作。
- 同步:同步可验证测试是否在界面空闲时执行操作或做出断言。
- 互操作性:借助互操作性,测试可以在同一应用中同时使用基于 Compose 和基于 View 的元素。
测试备忘单
如需概览有关在 Compose 中进行测试的所有关键主题,请参阅测试备忘单。
设置
设置应用,以便您测试 Compose 代码。
首先,将以下依赖项添加到包含界面测试的模块的 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 实现。通过此规则,您可以设置 Compose 内容或访问 activity。您可以使用工厂函数(createComposeRule
或 createAndroidComposeRule
,如果您需要访问 activity)来构建规则。Compose 的典型界面测试如下所示:
// 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 的界面,但其知识仍有助于进行 Compose 测试的某些方面。
Codelab
如需了解详情,请参阅 Jetpack Compose 测试 Codelab。
示例
为您推荐
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):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"]],["最后更新时间 (UTC):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)"]]