互操作性

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 等可滚动可组合项),启用此行为非常有用。

仅在可组合项层次结构中的较高层级启用语义属性一次,以确保可以通过 UiAutomator 访问所有带有 Modifier.testTag 的嵌套可组合项。

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) 的可组合项均可通过使用与 resourceName 相同的 tagBy.res(resourceName) 进行访问。

val device = UiDevice.getInstance(getInstrumentation())

val lazyColumn: UiObject2 = device.findObject(By.res("myLazyColumn"))
// Some interaction with the lazyColumn.

其他资源

  • 在 Android 平台上测试应用:Android 测试主着陆页让您更全面地了解测试基础知识和技术。
  • 测试基础知识:详细了解测试 Android 应用背后的核心概念。
  • 本地测试:您可以在自己的工作站上,在本地运行一些测试。
  • 插桩测试:最好同时运行插桩测试。也就是说,直接在设备上运行的测试。
  • 持续集成:借助持续集成,您可以将测试集成到部署流水线中。
  • 测试不同的屏幕尺寸:面对很多设备,用户应针对不同的屏幕尺寸进行测试。
  • Espresso:虽然适用于基于 View 的界面,但 Espresso 知识对于 Compose 测试的某些方面仍然很有帮助。