injecting-touch-gestures
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseInjecting Touch Gestures — performTouchInput, Not performGesture
注入触摸手势——使用 performTouchInput,而非 performGesture
performTouchInput { … }TouchInjectionScopeperformGesture { … }@Deprecated("Replaced by performTouchInput")performTouchInput { … }TouchInjectionScopeperformGesture { … }@Deprecated("Replaced by performTouchInput")When to use this skill
何时使用此 skill
- The test must simulate a partial gesture, multi-touch, fling with controlled velocity, or pinch-to-zoom — anything richer than a single tap.
- The developer needs precise coordinates relative to a node (e.g. drag by exactly 100 px from ).
center - A gesture must be split across two blocks while a finger is still "down".
performTouchInput - A test currently uses and must be migrated.
performGesture { } - A test simulates touch with hardcoded screen coordinates and is flaky on different display sizes.
- 测试需要模拟部分手势、多点触控、受控速度的 fling 或双指缩放——即任何比单次点击更复杂的手势。
- 开发者需要相对于节点的精确坐标(例如从 精确拖动 100 px)。
center - 需要在手指仍处于“按下”状态时,将一个手势拆分到两个 块中执行。
performTouchInput - 测试当前使用 ,需要进行迁移。
performGesture { } - 测试使用硬编码屏幕坐标模拟触摸,导致在不同显示尺寸下不稳定。
When NOT to use this skill
何时不应使用此 skill
- A simple tap on a node — use from
performClick(). It is platform-appropriate and shorter.../clicking-and-scrolling/SKILL.md - The gesture is a hover, right-click, or scroll wheel — use .
../injecting-mouse-and-keyboard/SKILL.md - The flow is "tap a button, then assert a Snackbar appears" — assert via , not by inspecting touch state.
../../assertions/asserting-node-state-and-text/SKILL.md - The test is fighting a fling animation — pause the clock first per .
../../synchronization/testing-animations-deterministically/SKILL.md
- 只是点击节点——使用 中的
../clicking-and-scrolling/SKILL.md。它更符合平台语义且更加简洁。performClick() - 手势属于悬停、右键单击或滚轮操作——使用 。
../injecting-mouse-and-keyboard/SKILL.md - 流程是“点击按钮,然后断言 Snackbar 出现”——通过 进行断言,而不是检查触摸状态。
../../assertions/asserting-node-state-and-text/SKILL.md - 测试正在与 fling 动画竞争——应先按照 暂停测试时钟。
../../synchronization/testing-animations-deterministically/SKILL.md
Prerequisites
前置条件
- (or
androidx.compose.ui:ui-test-junit4forui-test) configured perrunComposeUiTest.../../setup/configuring-test-dependencies/SKILL.md - The receiver node carries from production code so the test selects it deterministically.
Modifier.testTag("…") - For multi-touch gestures (,
pinch), the target composable accepts pointer input viamultiTouchSwipe— typicallyModifier.pointerInput { … },Modifier.transformable, or a customModifier.draggable2D.detectTransformGestures
- 已按照 配置
../../setup/configuring-test-dependencies/SKILL.md(或为androidx.compose.ui:ui-test-junit4配置runComposeUiTest)。ui-test - 接收手势的节点在生产代码中带有 ,以便测试能够确定性地选择该节点。
Modifier.testTag("…") - 对于多点触控手势(、
pinch),目标 composable 通过multiTouchSwipe接受指针输入——通常使用Modifier.pointerInput { … }、Modifier.transformable或自定义的Modifier.draggable2D。detectTransformGestures
Workflow
工作流程
- Acquire the receiver. is an extension on
performTouchInput. Find the node first.SemanticsNodeInteraction
kotlin
rule.onNodeWithTag(DragSurfaceTag).performTouchInput { /* DSL */ }-
Use node-local coordinates. Inside the block,is the node's top-left. Reach for the geometry helpers from
(0, 0)(InjectionScope.kt:34-206):InjectionScope,center,topLeft,topCenter,topRight,centerLeft,centerRight,bottomLeft,bottomCenter,bottomRight,width, plusheightandright == width - 1f(pixels are 0-based — InjectionScope.kt:96-112). Usebottom == height - 1ffor relative positioning. MUST NOT hardcode screen coordinates.percentOffset(.5f, .5f) -
Pick the right level of abstraction. High-level helpers cover most cases:
| Helper | Default | What it does |
|---|---|---|
| tap at center | |
| 100 ms past the long-press timeout | press, hold, release (TouchInjectionScope.kt:390) |
| midway between min/max double-tap window | |
| 200 ms linear | linear interpolation between two points (TouchInjectionScope.kt:445) |
| along axis through center | edge-to-edge sweeps (TouchInjectionScope.kt:649+) |
| computed for feasibility | shapes the path so the final velocity matches (TouchInjectionScope.kt:617) |
| 400 ms two-pointer | two simultaneous linear paths (TouchInjectionScope.kt:574) |
| — | one curve per pointer id (TouchInjectionScope.kt:491) |
-
Drop to low-level events for partial gestures. All in(TouchInjectionScope.kt):
TouchInjectionScope- — start a pointer at
down(pointerId = 0, position).position - — enqueue a move event.
moveTo(pointerId = 0, position, delayMillis = eventPeriodMillis) - — relative form.
moveBy(pointerId = 0, delta, delayMillis = eventPeriodMillis) - /
updatePointerTo(pointerId, position)— adjust the pointer position without enqueueing a move; useful when batching multiple pointer updates into a singleupdatePointerBy(pointerId, delta)call.move(delayMillis) - — flush a move event combining every pending pointer update.
move(delayMillis = eventPeriodMillis) - — release.
up(pointerId = 0) - — emit a
cancel(delayMillis = eventPeriodMillis)-equivalent.MotionEvent.ACTION_CANCEL - — query the last-known position of a pointer.
currentPosition(pointerId = 0): Offset?
-
Split gestures across blocks when recomposition matters mid-gesture. Pointer state is shared acrossinvocations on the same node — a pointer left "down" stays down. Use this to assert state at a frame the gesture passes through.
performTouchInput
kotlin
rule.onNodeWithTag(Tag).performTouchInput { down(center) }
// recomposition + assertions happen here
rule.onNodeWithTag(Tag).performTouchInput { moveBy(Offset(0f, 100f)); up() }Subsequent invocations on a different node remap pointer positions into that node's local space (TouchInjectionScope.kt:50-55), so positions are still local, not screen-global.
- Trust event batching. Every event enqueued inside one block is sent as one batch when the block returns; recomposition cannot interleave inside a block (Actions.kt:362-377). That is why all coordinates are resolved up front — and why a moving target does not invalidate the gesture inside one block.
performTouchInput
- 获取接收手势的节点。 是
performTouchInput的扩展函数。首先查找节点。SemanticsNodeInteraction
kotlin
rule.onNodeWithTag(DragSurfaceTag).performTouchInput { /* DSL */ }-
使用节点局部坐标。 在代码块内部,位于节点左上角。使用
(0, 0)中的几何辅助函数(InjectionScope.kt:34-206):InjectionScope、center、topLeft、topCenter、topRight、centerLeft、centerRight、bottomLeft、bottomCenter、bottomRight、width,以及height和right == width - 1f(像素从 0 开始计数——InjectionScope.kt:96-112)。使用bottom == height - 1f进行相对定位。不得硬编码屏幕坐标。percentOffset(.5f, .5f) -
选择合适的抽象层级。 大多数场景可以使用高级辅助函数:
| 辅助函数 | 默认值 | 作用 |
|---|---|---|
| | 在中心位置点击;执行 |
| 超过长按时限 100 ms | 按下、保持并释放(TouchInjectionScope.kt:390) |
| 最小与最大双击时间窗口的中间值 | 执行 |
| 200 ms 线性移动 | 在两个点之间进行线性插值(TouchInjectionScope.kt:445) |
| 沿穿过中心的轴移动 | 从一边到另一边进行扫动(TouchInjectionScope.kt:649+) |
| 根据可行性计算 | 调整路径形状,使最终速度与目标速度匹配(TouchInjectionScope.kt:617) |
| 400 ms 双指针 | 两条同时发生的线性路径(TouchInjectionScope.kt:574) |
| — | 每个指针 ID 对应一条曲线(TouchInjectionScope.kt:491) |
-
部分手势应使用底层事件。 以下方法均位于(TouchInjectionScope.kt)中:
TouchInjectionScope- ——在
down(pointerId = 0, position)位置启动一个指针。position - ——将移动事件加入队列。
moveTo(pointerId = 0, position, delayMillis = eventPeriodMillis) - ——以相对形式移动。
moveBy(pointerId = 0, delta, delayMillis = eventPeriodMillis) - /
updatePointerTo(pointerId, position)——调整指针位置,但不会将移动事件加入队列;适用于将多个指针更新合并到单次updatePointerBy(pointerId, delta)调用中。move(delayMillis) - ——刷新一次移动事件,其中包含所有待处理的指针更新。
move(delayMillis = eventPeriodMillis) - ——释放指针。
up(pointerId = 0) - ——发出等同于
cancel(delayMillis = eventPeriodMillis)的事件。MotionEvent.ACTION_CANCEL - ——查询指针最后已知的位置。
currentPosition(pointerId = 0): Offset?
-
当重组在手势中途发生时,将手势拆分到多个块中。 同一节点上的多次调用共享指针状态——处于“按下”状态的指针会保持按下。可以利用这一点,在手势经过的某一帧断言状态。
performTouchInput
kotlin
rule.onNodeWithTag(Tag).performTouchInput { down(center) }
// recomposition + assertions happen here
rule.onNodeWithTag(Tag).performTouchInput { moveBy(Offset(0f, 100f)); up() }后续在不同节点上调用时,指针位置会被重新映射到该节点的局部空间(TouchInjectionScope.kt:50-55),因此这些位置仍是局部坐标,而不是全局屏幕坐标。
- 信任事件批处理机制。 在同一个 块内加入队列的所有事件,都会在块返回时作为单个批次发送;重组无法在块内穿插执行(Actions.kt:362-377)。这就是为什么所有坐标都会预先解析——移动中的目标不会使同一个块内的手势失效。
performTouchInput
Patterns
模式
Pattern: Replace performGesture with performTouchInput
模式:使用 performTouchInput 替换 performGesture
kotlin
// WRONG
@Suppress("DEPRECATION")
rule.onNodeWithTag(Tag).performGesture { swipeUp() }
// WRONG because: performGesture is @Deprecated("Replaced by performTouchInput") (Actions.kt:337).
// The replaceWith metadata in the @Deprecated annotation explicitly suggests performTouchInput.kotlin
// RIGHT
rule.onNodeWithTag(Tag).performTouchInput { swipeUp() }This is a non-negotiable migration. exists only for binary compatibility.
performGesturekotlin
// WRONG
@Suppress("DEPRECATION")
rule.onNodeWithTag(Tag).performGesture { swipeUp() }
// WRONG because: performGesture is @Deprecated("Replaced by performTouchInput") (Actions.kt:337).
// The replaceWith metadata in the @Deprecated annotation explicitly suggests performTouchInput.kotlin
// RIGHT
rule.onNodeWithTag(Tag).performTouchInput { swipeUp() }这是不可妥协的迁移要求。 仅保留用于二进制兼容性。
performGesturePattern: Hardcoded screen coordinates vs node-local
模式:硬编码屏幕坐标与节点局部坐标
kotlin
// WRONG
rule.onNodeWithTag(Tag).performTouchInput {
down(Offset(500f, 800f))
moveTo(Offset(500f, 700f))
up()
}
// WRONG because: (500, 800) only happens to land on the node on certain device profiles.
// On a tablet or in landscape the node sits elsewhere, and on a small phone it may not even
// be inside the visible bounds — the test becomes device-shaped.kotlin
// RIGHT
rule.onNodeWithTag(Tag).performTouchInput {
down(center)
moveBy(Offset(0f, -100f))
up()
}centerbottomCentertopRightvisibleSizekotlin
// WRONG
rule.onNodeWithTag(Tag).performTouchInput {
down(Offset(500f, 800f))
moveTo(Offset(500f, 700f))
up()
}
// WRONG because: (500, 800) only happens to land on the node on certain device profiles.
// On a tablet or in landscape the node sits elsewhere, and on a small phone it may not even
// be inside the visible bounds — the test becomes device-shaped.kotlin
// RIGHT
rule.onNodeWithTag(Tag).performTouchInput {
down(center)
moveBy(Offset(0f, -100f))
up()
}centerbottomCentertopRightvisibleSizePattern: Real swipe from DraggableTest
模式:DraggableTest 中的真实滑动
The canonical horizontal-drag pattern from :
DraggableTest.kt:114-146kotlin
@Test
fun draggable_horizontalDrag() {
var total = 0f
setDraggableContent { Modifier.draggable(Orientation.Horizontal) { total += it } }
rule.onNodeWithTag(draggableBoxTag).performTouchInput {
this.swipe(
start = this.center,
end = Offset(this.center.x + 100f, this.center.y),
durationMillis = 100,
)
}
val lastTotal = rule.runOnIdle {
assertThat(total).isGreaterThan(0)
total
}
}Notes worth copying: makes the receiver explicit (handy when nesting blocks); keeps the test fast; the assertion runs inside (skydoves hot take #5).
this.centerdurationMillis = 100runOnIdle来自 的标准水平拖动模式:
DraggableTest.kt:114-146kotlin
@Test
fun draggable_horizontalDrag() {
var total = 0f
setDraggableContent { Modifier.draggable(Orientation.Horizontal) { total += it } }
rule.onNodeWithTag(draggableBoxTag).performTouchInput {
this.swipe(
start = this.center,
end = Offset(this.center.x + 100f, this.center.y),
durationMillis = 100,
)
}
val lastTotal = rule.runOnIdle {
assertThat(total).isGreaterThan(0)
total
}
}值得复制的要点: 能够明确指定接收者(嵌套代码块时尤其方便); 可以让测试保持快速;断言在 内部运行(skydoves 热门观点 #5)。
this.centerdurationMillis = 100runOnIdlePattern: Pinch-to-zoom
模式:双指缩放
From :
TransformableTest.kt:128-141kotlin
rule.onNodeWithTag(TEST_TAG).performTouchInput {
val leftStartX = center.x - 10
val leftEndX = visibleSize.toSize().width * EDGE_FUZZ_FACTOR
val rightStartX = center.x + 10
val rightEndX = visibleSize.toSize().width * (1 - EDGE_FUZZ_FACTOR)
pinch(
Offset(leftStartX, center.y),
Offset(leftEndX, center.y),
Offset(rightStartX, center.y),
Offset(rightEndX, center.y),
)
}pinch(start0, end0, start1, end1)durationMillis = 400EDGE_FUZZ_FACTOR0.05f0fright == width - 1f来自 :
TransformableTest.kt:128-141kotlin
rule.onNodeWithTag(TEST_TAG).performTouchInput {
val leftStartX = center.x - 10
val leftEndX = visibleSize.toSize().width * EDGE_FUZZ_FACTOR
val rightStartX = center.x + 10
val rightEndX = visibleSize.toSize().width * (1 - EDGE_FUZZ_FACTOR)
pinch(
Offset(leftStartX, center.y),
Offset(leftEndX, center.y),
Offset(rightStartX, center.y),
Offset(rightEndX, center.y),
)
}pinch(start0, end0, start1, end1)durationMillis = 400EDGE_FUZZ_FACTOR0.05f0fright == width - 1fPattern: Split gesture for mid-gesture assertion
模式:拆分手势以进行手势中途断言
kotlin
@Test fun longPress_thenAssert_thenRelease() {
rule.setContent { /* … */ }
// Hold finger down at center, do not release.
rule.onNodeWithTag(Tag).performTouchInput { down(center) }
// Wait for the long-press timeout to elapse via the test clock.
rule.mainClock.advanceTimeBy(viewConfiguration.longPressTimeoutMillis + 100)
rule.onNodeWithTag(Tag).assertHasIndicationOfLongPress() // your assertion
// Release in a second block; the pointer is still "down" between blocks.
rule.onNodeWithTag(Tag).performTouchInput { up() }
}Pointer state survives across blocks; the recomposer runs between them. This is how exercises haptic-feedback-on-long-press paths (e.g. ).
CombinedClickableTestCombinedClickableTest.kt:446-471kotlin
@Test fun longPress_thenAssert_thenRelease() {
rule.setContent { /* … */ }
// Hold finger down at center, do not release.
rule.onNodeWithTag(Tag).performTouchInput { down(center) }
// Wait for the long-press timeout to elapse via the test clock.
rule.mainClock.advanceTimeBy(viewConfiguration.longPressTimeoutMillis + 100)
rule.onNodeWithTag(Tag).assertHasIndicationOfLongPress() // your assertion
// Release in a second block; the pointer is still "down" between blocks.
rule.onNodeWithTag(Tag).performTouchInput { up() }
}指针状态会在多个块之间保留,而重组器会在两个块之间运行。 正是通过这种方式测试长按触觉反馈路径(例如 )。
CombinedClickableTestCombinedClickableTest.kt:446-471Pattern: Velocity-controlled fling
模式:速度可控的 fling
kotlin
rule.onNodeWithTag(Tag).performTouchInput {
swipeWithVelocity(
start = bottomCenter,
end = topCenter,
endVelocity = 4_000f, // px/second
durationMillis = 200,
)
}swipeWithVelocityIllegalArgumentExceptionkotlin
rule.onNodeWithTag(Tag).performTouchInput {
swipeWithVelocity(
start = bottomCenter,
end = topCenter,
endVelocity = 4_000f, // px/second
durationMillis = 200,
)
}swipeWithVelocityIllegalArgumentExceptionMandatory rules
强制规则
- MUST use . MUST NOT use
performTouchInput { … }— it isperformGesture { … }(Actions.kt:337-355). This is non-negotiable.@Deprecated - MUST express coordinates in the node-local system using ,
center,topLeft,bottomRight, etc. MUST NOT hardcode screen pixel coordinates — the test will be device-shaped.percentOffset(...) - MUST route post-gesture state assertions through (skydoves hot take #5). Reading
rule.runOnIdle { … }on the test thread races with the recomposer that processed the gesture.state - MUST advance the test clock with between split
rule.mainClock.advanceTimeBy(...)blocks when the test depends on a duration (long-press, double-tap window). MUST NOT useperformTouchInput— seeThread.sleep.../../synchronization/synchronizing-with-idle/SKILL.md - PREFERRED: start every drag from and use
centerwith relative deltas. Absolute paths (moveBy) work but read worse and break under RTL layouts.moveTo(topLeft) - PREFERRED: pick for monotonic linear motion,
swipeonly when fling behaviour is under test, andswipeWithVelocityonly for >2 pointers or non-linear curves.multiTouchSwipe
- 必须使用 。不得使用
performTouchInput { … }——它已被标记为performGesture { … }(Actions.kt:337-355)。这是不可妥协的要求。@Deprecated - 必须使用 、
center、topLeft、bottomRight等方式在节点局部坐标系中表达坐标。不得硬编码屏幕像素坐标——否则测试会受设备尺寸影响。percentOffset(...) - 必须通过 执行手势后的状态断言(skydoves 热门观点 #5)。在测试线程上读取
rule.runOnIdle { … }会与处理该手势的重组器产生竞争。state - 当测试依赖某个持续时间(长按、双击时间窗口)时,必须在拆分后的 块之间使用
performTouchInput推进测试时钟。不得使用rule.mainClock.advanceTimeBy(...)——参见Thread.sleep。../../synchronization/synchronizing-with-idle/SKILL.md - **推荐:**每次拖动都从 开始,并使用
center和相对增量。绝对路径(如moveBy)虽然有效,但可读性更差,并且在 RTL 布局下容易失效。moveTo(topLeft) - **推荐:**单调线性移动使用 ;仅当需要测试 fling 行为时使用
swipe;仅当需要超过 2 个指针或非线性曲线时使用swipeWithVelocity。multiTouchSwipe
Verification
验证
- No occurrence of in the test source set:
performGesturereturns nothing.git grep -n 'performGesture' src/androidTest src/test - No inside or between
Thread.sleepblocks (skydoves hot take #7).performTouchInput - No hardcoded in the test — every position resolves through
Offset(<screen-pixel>, <screen-pixel>),center,top*,bottom*, etc.centerLeft - Assertions following a touch gesture run inside .
rule.runOnIdle { … } - (or
./gradlew :app:connectedDebugAndroidTest) passes for the test under change.:app:testDebugUnitTest
- 测试源集中不存在 :
performGesture不返回任何结果。git grep -n 'performGesture' src/androidTest src/test - 块内部或块之间不存在
performTouchInput(skydoves 热门观点 #7)。Thread.sleep - 测试中不存在硬编码的 ——每个位置都通过
Offset(<screen-pixel>, <screen-pixel>)、center、top*、bottom*等方式解析。centerLeft - 触摸手势后的断言在 内部运行。
rule.runOnIdle { … } - (或
./gradlew :app:connectedDebugAndroidTest)能够通过本次修改涉及的测试。:app:testDebugUnitTest
References
参考资料
- Compose testing overview: https://developer.android.com/develop/ui/compose/testing
- Compose testing cheat sheet: https://developer.android.com/develop/ui/compose/testing-cheatsheet
- —
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Actions.kt(Actions.kt:399),performTouchInputdeprecation (Actions.kt:337-355).performGesture - — DSL surface (
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/TouchInjectionScope.kt,down,moveTo,moveBy,up,cancel,click,longClick,doubleClick,swipe/swipeUp/Down/Left,Right,swipeWithVelocity,pinch).multiTouchSwipe - — geometry helpers (
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/InjectionScope.kt,center,topLeft,topCenter,bottomRight,width,height,right,bottom,percentOffset,visibleSize).advanceEventTime - — canonical
compose/foundation/foundation/src/androidDeviceTest/.../DraggableTest.kt(DraggableTest.kt:114-146).swipe(start, end, durationMillis) - —
compose/foundation/foundation/src/androidDeviceTest/.../TransformableTest.ktfour-point gesture (TransformableTest.kt:128-141).pinch(...) - —
compose/foundation/foundation/src/androidDeviceTest/.../CombinedClickableTest.kt, splitperformTouchInput { longClick() }/down(center)blocks for haptic tests.up() - — low-level
compose/foundation/foundation/src/androidDeviceTest/.../ScrollableAreaTest.ktflow.down(); moveBy() - skydoves — compose-performance-skills: https://github.com/skydoves/compose-performance-skills
- Compose 测试概览:https://developer.android.com/develop/ui/compose/testing
- Compose 测试速查表:https://developer.android.com/develop/ui/compose/testing-cheatsheet
- ——
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Actions.kt(Actions.kt:399),以及performTouchInput弃用说明(Actions.kt:337-355)。performGesture - ——DSL 接口(
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/TouchInjectionScope.kt、down、moveTo、moveBy、up、cancel、click、longClick、doubleClick、swipe/swipeUp/Down/Left、Right、swipeWithVelocity、pinch)。multiTouchSwipe - ——几何辅助函数(
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/InjectionScope.kt、center、topLeft、topCenter、bottomRight、width、height、right、bottom、percentOffset、visibleSize)。advanceEventTime - ——标准的
compose/foundation/foundation/src/androidDeviceTest/.../DraggableTest.kt(DraggableTest.kt:114-146)。swipe(start, end, durationMillis) - ——四点
compose/foundation/foundation/src/androidDeviceTest/.../TransformableTest.kt手势(TransformableTest.kt:128-141)。pinch(...) - ——
compose/foundation/foundation/src/androidDeviceTest/.../CombinedClickableTest.kt,以及为触觉测试拆分performTouchInput { longClick() }/down(center)代码块。up() - ——底层
compose/foundation/foundation/src/androidDeviceTest/.../ScrollableAreaTest.kt流程。down(); moveBy() - skydoves——compose-performance-skills:https://github.com/skydoves/compose-performance-skills