测试 Compose 布局

测试应用的界面,以验证 Compose 代码的行为是否正确。这样,您就可以尽早发现错误并提升应用质量。

Compose 提供了一组测试 API,用于查找元素、验证其属性以及执行用户操作。这些 API 还包括时间控制等高级功能。使用这些 API 创建可靠的测试来验证应用的行为。

View

如果您使用的是 View 而非 Compose,请参阅常规的在 Android 上测试应用部分。

建议您先参阅自动化界面测试指南。其中介绍了如何自动运行设备端测试,包括使用 View 时。

关键概念

以下是测试 Compose 代码的一些关键概念。

  • 语义:Compose 测试使用语义与界面进行交互,语义为界面各部分赋予意义,并与界面层次结构一起生成。
  • 测试 API:Compose 提供了测试 API,用于查找元素、对其状态和属性进行断言,以及执行操作来模拟用户互动。
  • 同步:默认情况下,Compose 测试会自动与界面同步,等待界面处于空闲状态后再进行断言或执行操作。
  • 互操作性:在混合应用中,测试可以与 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)构建规则,如果您需要访问 activity,则可以使用 createAndroidComposeRule。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 测试的某些方面,Espresso 知识仍然很有帮助。

Codelab

如需了解详情,请参阅 Jetpack Compose 测试 Codelab

示例

Jetchat is a sample chat app built with Jetpack Compose. To try out this sample app, use the latest stable version of Android Studio. You can clone this repository or import the project from Android Studio following the steps here. This sample

Jetnews is a sample news reading app, built with Jetpack Compose. The goal of the sample is to showcase the current UI capabilities of Compose. To try out this sample app, use the latest stable version of Android Studio. You can clone this repository

Learn how this app was designed and built in the design case study, architecture learning journey and modularization learning journey. This is the repository for the Now in Android app. It is a work in progress 🚧. Now in Android is a fully functional