返回

Compose 测试:如何通过滑动执行取消操作?

Android

## Compose 测试:通过滑动取消操作

定位目标文本项

在 Compose 测试中模拟滑动操作的第一步是使用 onNodeWithText() 方法定位目标文本项。这将返回一个代表文本节点的 UiNode 对象。例如,以下代码将定位包含文本 "title" 的文本项:

val emailNode = onNodeWithText("title")

触发滑动动作

要触发滑动动作,请调用 performTouchInput() 方法并指定开始和结束位置。使用 swipeRight() 方法可以轻松地向右滑动:

emailNode.performTouchInput {
    swipeRight()
}

断言滑动回调被调用

在测试中,断言 swipe callback 是否被调用至关重要。可以使用 MatcherAssert 来实现这一点:

MatcherAssert.assertThat(isDeleted, Matchers.equalTo(true))

示例测试

以下示例测试验证了向右滑动时是否触发了删除操作:

// ... (设置和内容与以前相同)

@Test
fun validateThatSwipeActionIsGreaterThanThresholdThenDeleteActionIsTaken() {
    var isDeleted = false
    composeRule.setContent {
        JetpackComposeAuthenticationTheme {
            EmailContentList(modifier = Modifier.fillMaxSize(), emails = emails) {
                isDeleted = true
            }
        }
    }

    composeRule.run {
        emails.forEachIndexed { index, email ->
            onNodeWithTag(TAG_CONTENT).onChildAt(index).performScrollTo().performTouchInput {
                swipeRight()
            }

            MatcherAssert.assertThat(isDeleted, Matchers.equalTo(true))
        }
    }
}

常见问题解答

1. 为什么我无法在测试中触发滑动?

  • 确保你使用的是正确的 UiNode 对象,并且目标项可见且可交互。

2. 如何测试滑动的方向和距离?

  • 使用 performTouchInput() 方法的 directiondistance 参数来指定滑动方向和距离。

3. 如何在测试中模拟长按并滑动?

  • 使用 performLongPress() 方法进行长按,然后使用 performTouchInput() 方法进行滑动。

4. 如何断言滑动是否超过特定阈值?

  • 使用 MatcherAssert 比较滑动的距离或时间与阈值。

5. 如何在 Compose 测试中测试其他手势?

  • Jetpack Compose 测试库提供了各种 perform*Input() 方法来测试捏合、缩放和旋转等手势。