互操作性

Compose 集成了常见的测试框架。

与 Espresso 的互操作性

在混合应用中,您可以在视图层次结构中找到 Compose 组件,并在 Compose 可组合项中找到视图(通过 AndroidView 可组合项)。

匹配任一类型都不需要特殊步骤。您可以使用 Espresso 的 onView 来匹配视图,并使用 ComposeTestRule 来匹配 Compose 元素。

@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) 来访问,其中 tagresourceName 相同。

val device = UiDevice.getInstance(getInstrumentation())

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

其他资源

  • 在 Android 上测试应用:主要的 Android 测试着陆页提供了测试基础知识和技术更广阔的视角。
  • 测试基础知识详细了解测试 Android 应用背后的核心概念。
  • 本地测试您可以在本地工作站上运行某些测试。
  • 插桩测试运行插桩测试也是一种好做法。即直接在设备上运行的测试。
  • 持续集成持续集成可让您将测试集成到部署流水线中。
  • 测试不同的屏幕尺寸由于用户可用的设备种类繁多,您应该测试不同的屏幕尺寸。
  • Espresso:虽然 Espresso 适用于基于 View 的界面,但 Espresso 知识对于 Compose 测试的某些方面仍然很有帮助。