injecting-touch-gestures

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Injecting Touch Gestures — performTouchInput, Not performGesture

注入触摸手势——使用 performTouchInput,而非 performGesture

performTouchInput { … }
is the single entry point for synthetic touch events in Compose tests. It runs a block in a
TouchInjectionScope
whose coordinate system is node-local (origin at the node's top-left), batches every event the block enqueues, and flushes them as a single non-recomposing burst when the block returns. The legacy
performGesture { … }
is
@Deprecated("Replaced by performTouchInput")
(Actions.kt:337-355) — MUST NOT appear in any new code.
performTouchInput { … }
是 Compose 测试中合成触摸事件的唯一入口。它在
TouchInjectionScope
中运行代码块,该作用域采用节点局部坐标系(原点位于节点左上角),会将代码块排队的每个事件进行批处理,并在代码块返回时将其一次性刷新为单个不触发重组的事件批次。旧版
performGesture { … }
已标记为
@Deprecated("Replaced by performTouchInput")
(Actions.kt:337-355)——任何新代码中都不得出现。

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
    performTouchInput
    blocks while a finger is still "down".
  • A test currently uses
    performGesture { }
    and must be migrated.
  • A test simulates touch with hardcoded screen coordinates and is flaky on different display sizes.
  • 测试需要模拟部分手势、多点触控、受控速度的 fling 或双指缩放——即任何比单次点击更复杂的手势。
  • 开发者需要相对于节点的精确坐标(例如从
    center
    精确拖动 100 px)。
  • 需要在手指仍处于“按下”状态时,将一个手势拆分到两个
    performTouchInput
    块中执行。
  • 测试当前使用
    performGesture { }
    ,需要进行迁移。
  • 测试使用硬编码屏幕坐标模拟触摸,导致在不同显示尺寸下不稳定。

When NOT to use this skill

何时不应使用此 skill

  • A simple tap on a node — use
    performClick()
    from
    ../clicking-and-scrolling/SKILL.md
    . It is platform-appropriate and shorter.
  • 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
    ../../assertions/asserting-node-state-and-text/SKILL.md
    , not by inspecting touch state.
  • 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

前置条件

  • androidx.compose.ui:ui-test-junit4
    (or
    ui-test
    for
    runComposeUiTest
    ) configured per
    ../../setup/configuring-test-dependencies/SKILL.md
    .
  • The receiver node carries
    Modifier.testTag("…")
    from production code so the test selects it deterministically.
  • For multi-touch gestures (
    pinch
    ,
    multiTouchSwipe
    ), the target composable accepts pointer input via
    Modifier.pointerInput { … }
    — typically
    Modifier.transformable
    ,
    Modifier.draggable2D
    , or a custom
    detectTransformGestures
    .
  • 已按照
    ../../setup/configuring-test-dependencies/SKILL.md
    配置
    androidx.compose.ui:ui-test-junit4
    (或为
    runComposeUiTest
    配置
    ui-test
    )。
  • 接收手势的节点在生产代码中带有
    Modifier.testTag("…")
    ,以便测试能够确定性地选择该节点。
  • 对于多点触控手势(
    pinch
    、
    multiTouchSwipe
    ),目标 composable 通过
    Modifier.pointerInput { … }
    接受指针输入——通常使用
    Modifier.transformable
    、
    Modifier.draggable2D
    或自定义的
    detectTransformGestures
    。

Workflow

工作流程

  1. Acquire the receiver.
    performTouchInput
    is an extension on
    SemanticsNodeInteraction
    . Find the node first.
kotlin
rule.onNodeWithTag(DragSurfaceTag).performTouchInput { /* DSL */ }
  1. Use node-local coordinates. Inside the block,
    (0, 0)
    is the node's top-left. Reach for the geometry helpers from
    InjectionScope
    (InjectionScope.kt:34-206):
    center
    ,
    topLeft
    ,
    topCenter
    ,
    topRight
    ,
    centerLeft
    ,
    centerRight
    ,
    bottomLeft
    ,
    bottomCenter
    ,
    bottomRight
    ,
    width
    ,
    height
    , plus
    right == width - 1f
    and
    bottom == height - 1f
    (pixels are 0-based — InjectionScope.kt:96-112). Use
    percentOffset(.5f, .5f)
    for relative positioning. MUST NOT hardcode screen coordinates.
  2. Pick the right level of abstraction. High-level helpers cover most cases:
HelperDefaultWhat it does
click(position = center)
tap at center
down(); move(); up()
(TouchInjectionScope.kt:372)
longClick(position = center, durationMillis = vc.longPressTimeoutMillis + 100)
100 ms past the long-press timeoutpress, hold, release (TouchInjectionScope.kt:390)
doubleClick(position = center, delayMillis = …)
midway between min/max double-tap window
click(); advanceEventTime(delay); click()
(TouchInjectionScope.kt:417)
swipe(start, end, durationMillis = 200)
200 ms linearlinear interpolation between two points (TouchInjectionScope.kt:445)
swipeUp / swipeDown / swipeLeft / swipeRight
along axis through centeredge-to-edge sweeps (TouchInjectionScope.kt:649+)
swipeWithVelocity(start, end, endVelocity, durationMillis)
computed for feasibilityshapes the path so the final velocity matches (TouchInjectionScope.kt:617)
pinch(start0, end0, start1, end1, durationMillis = 400)
400 ms two-pointertwo simultaneous linear paths (TouchInjectionScope.kt:574)
multiTouchSwipe(curves, durationMillis, keyTimes)
—one curve per pointer id (TouchInjectionScope.kt:491)
  1. Drop to low-level events for partial gestures. All in
    TouchInjectionScope
    (TouchInjectionScope.kt):
    • down(pointerId = 0, position)
      — start a pointer at
      position
      .
    • moveTo(pointerId = 0, position, delayMillis = eventPeriodMillis)
      — enqueue a move event.
    • moveBy(pointerId = 0, delta, delayMillis = eventPeriodMillis)
      — relative form.
    • updatePointerTo(pointerId, position)
      /
      updatePointerBy(pointerId, delta)
      — adjust the pointer position without enqueueing a move; useful when batching multiple pointer updates into a single
      move(delayMillis)
      call.
    • move(delayMillis = eventPeriodMillis)
      — flush a move event combining every pending pointer update.
    • up(pointerId = 0)
      — release.
    • cancel(delayMillis = eventPeriodMillis)
      — emit a
      MotionEvent.ACTION_CANCEL
      -equivalent.
    • currentPosition(pointerId = 0): Offset?
      — query the last-known position of a pointer.
  2. Split gestures across blocks when recomposition matters mid-gesture. Pointer state is shared across
    performTouchInput
    invocations on the same node — a pointer left "down" stays down. Use this to assert state at a frame the gesture passes through.
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.
  1. Trust event batching. Every event enqueued inside one
    performTouchInput
    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.
  1. 获取接收手势的节点。
    performTouchInput
    是
    SemanticsNodeInteraction
    的扩展函数。首先查找节点。
kotlin
rule.onNodeWithTag(DragSurfaceTag).performTouchInput { /* DSL */ }
  1. 使用节点局部坐标。 在代码块内部,
    (0, 0)
    位于节点左上角。使用
    InjectionScope
    中的几何辅助函数(InjectionScope.kt:34-206):
    center
    、
    topLeft
    、
    topCenter
    、
    topRight
    、
    centerLeft
    、
    centerRight
    、
    bottomLeft
    、
    bottomCenter
    、
    bottomRight
    、
    width
    、
    height
    ,以及
    right == width - 1f
    和
    bottom == height - 1f
    (像素从 0 开始计数——InjectionScope.kt:96-112)。使用
    percentOffset(.5f, .5f)
    进行相对定位。不得硬编码屏幕坐标。
  2. 选择合适的抽象层级。 大多数场景可以使用高级辅助函数:
辅助函数默认值作用
click(position = center)
center
在中心位置点击;执行
down(); move(); up()
(TouchInjectionScope.kt:372)
longClick(position = center, durationMillis = vc.longPressTimeoutMillis + 100)
超过长按时限 100 ms按下、保持并释放(TouchInjectionScope.kt:390)
doubleClick(position = center, delayMillis = …)
最小与最大双击时间窗口的中间值执行
click(); advanceEventTime(delay); click()
(TouchInjectionScope.kt:417)
swipe(start, end, durationMillis = 200)
200 ms 线性移动在两个点之间进行线性插值(TouchInjectionScope.kt:445)
swipeUp / swipeDown / swipeLeft / swipeRight
沿穿过中心的轴移动从一边到另一边进行扫动(TouchInjectionScope.kt:649+)
swipeWithVelocity(start, end, endVelocity, durationMillis)
根据可行性计算调整路径形状,使最终速度与目标速度匹配(TouchInjectionScope.kt:617)
pinch(start0, end0, start1, end1, durationMillis = 400)
400 ms 双指针两条同时发生的线性路径(TouchInjectionScope.kt:574)
multiTouchSwipe(curves, durationMillis, keyTimes)
—每个指针 ID 对应一条曲线(TouchInjectionScope.kt:491)
  1. 部分手势应使用底层事件。 以下方法均位于
    TouchInjectionScope
    (TouchInjectionScope.kt)中:
    • 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?
      ——查询指针最后已知的位置。
  2. 当重组在手势中途发生时,将手势拆分到多个块中。 同一节点上的多次
    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),因此这些位置仍是局部坐标,而不是全局屏幕坐标。
  1. 信任事件批处理机制。 在同一个
    performTouchInput
    块内加入队列的所有事件,都会在块返回时作为单个批次发送;重组无法在块内穿插执行(Actions.kt:362-377)。这就是为什么所有坐标都会预先解析——移动中的目标不会使同一个块内的手势失效。

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.
performGesture
exists only for binary compatibility.
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() }
这是不可妥协的迁移要求。
performGesture
仅保留用于二进制兼容性。

Pattern: 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()
}
center
,
bottomCenter
,
topRight
, etc. are derived from
visibleSize
of the node (InjectionScope.kt:49-50, :118-185). The test runs unchanged across screen sizes.
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()
}
center
、
bottomCenter
、
topRight
等坐标根据节点的
visibleSize
推导得出(InjectionScope.kt:49-50、:118-185)。无论屏幕尺寸如何,测试都可以保持不变。

Pattern: Real swipe from DraggableTest

模式:DraggableTest 中的真实滑动

The canonical horizontal-drag pattern from
DraggableTest.kt:114-146
:
kotlin
@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:
this.center
makes the receiver explicit (handy when nesting blocks);
durationMillis = 100
keeps the test fast; the assertion runs inside
runOnIdle
(skydoves hot take #5).
来自
DraggableTest.kt:114-146
的标准水平拖动模式:
kotlin
@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
    }
}
值得复制的要点:
this.center
能够明确指定接收者(嵌套代码块时尤其方便);
durationMillis = 100
可以让测试保持快速;断言在
runOnIdle
内部运行(skydoves 热门观点 #5)。

Pattern: Pinch-to-zoom

模式:双指缩放

From
TransformableTest.kt:128-141
:
kotlin
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)
interpolates two pointers in parallel for
durationMillis = 400
(TouchInjectionScope.kt:574-589). Use
EDGE_FUZZ_FACTOR
(e.g.
0.05f
) instead of
0f
to avoid landing exactly on the right/bottom edge —
right == width - 1f
, see InjectionScope.kt:96-102.
来自
TransformableTest.kt:128-141
:
kotlin
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 = 400
的时间内并行插值两个指针(TouchInjectionScope.kt:574-589)。使用
EDGE_FUZZ_FACTOR
(例如
0.05f
),而不是
0f
,以避免位置恰好落在右侧或底部边缘——参见
right == width - 1f
(InjectionScope.kt:96-102)。

Pattern: 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
CombinedClickableTest
exercises haptic-feedback-on-long-press paths (e.g.
CombinedClickableTest.kt:446-471
).
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() }
}
指针状态会在多个块之间保留,而重组器会在两个块之间运行。
CombinedClickableTest
正是通过这种方式测试长按触觉反馈路径(例如
CombinedClickableTest.kt:446-471
)。

Pattern: Velocity-controlled fling

模式:速度可控的 fling

kotlin
rule.onNodeWithTag(Tag).performTouchInput {
    swipeWithVelocity(
        start = bottomCenter,
        end = topCenter,
        endVelocity = 4_000f,         // px/second
        durationMillis = 200,
    )
}
swipeWithVelocity
shapes the path so the final velocity is within ~0.1 of the target (TouchInjectionScope.kt:617-637). The duration must be long enough for at least 3 input events (~40 ms minimum); the API throws
IllegalArgumentException
with a fix suggestion if the input is infeasible.
kotlin
rule.onNodeWithTag(Tag).performTouchInput {
    swipeWithVelocity(
        start = bottomCenter,
        end = topCenter,
        endVelocity = 4_000f,         // px/second
        durationMillis = 200,
    )
}
swipeWithVelocity
会调整路径形状,使最终速度与目标值的误差控制在约 0.1 以内(TouchInjectionScope.kt:617-637)。持续时间必须足够长,以便至少产生 3 个输入事件(最短约 40 ms);如果输入不可行,该 API 会抛出
IllegalArgumentException
并提供修复建议。

Mandatory rules

强制规则

  • MUST use
    performTouchInput { … }
    . MUST NOT use
    performGesture { … }
    — it is
    @Deprecated
    (Actions.kt:337-355). This is non-negotiable.
  • MUST express coordinates in the node-local system using
    center
    ,
    topLeft
    ,
    bottomRight
    ,
    percentOffset(...)
    , etc. MUST NOT hardcode screen pixel coordinates — the test will be device-shaped.
  • MUST route post-gesture state assertions through
    rule.runOnIdle { … }
    (skydoves hot take #5). Reading
    state
    on the test thread races with the recomposer that processed the gesture.
  • MUST advance the test clock with
    rule.mainClock.advanceTimeBy(...)
    between split
    performTouchInput
    blocks when the test depends on a duration (long-press, double-tap window). MUST NOT use
    Thread.sleep
    — see
    ../../synchronization/synchronizing-with-idle/SKILL.md
    .
  • PREFERRED: start every drag from
    center
    and use
    moveBy
    with relative deltas. Absolute paths (
    moveTo(topLeft)
    ) work but read worse and break under RTL layouts.
  • PREFERRED: pick
    swipe
    for monotonic linear motion,
    swipeWithVelocity
    only when fling behaviour is under test, and
    multiTouchSwipe
    only for >2 pointers or non-linear curves.
  • 必须使用
    performTouchInput { … }
    。不得使用
    performGesture { … }
    ——它已被标记为
    @Deprecated
    (Actions.kt:337-355)。这是不可妥协的要求。
  • 必须使用
    center
    、
    topLeft
    、
    bottomRight
    、
    percentOffset(...)
    等方式在节点局部坐标系中表达坐标。不得硬编码屏幕像素坐标——否则测试会受设备尺寸影响。
  • 必须通过
    rule.runOnIdle { … }
    执行手势后的状态断言(skydoves 热门观点 #5)。在测试线程上读取
    state
    会与处理该手势的重组器产生竞争。
  • 当测试依赖某个持续时间(长按、双击时间窗口)时,必须在拆分后的
    performTouchInput
    块之间使用
    rule.mainClock.advanceTimeBy(...)
    推进测试时钟。不得使用
    Thread.sleep
    ——参见
    ../../synchronization/synchronizing-with-idle/SKILL.md
    。
  • **推荐:**每次拖动都从
    center
    开始,并使用
    moveBy
    和相对增量。绝对路径(如
    moveTo(topLeft)
    )虽然有效,但可读性更差,并且在 RTL 布局下容易失效。
  • **推荐:**单调线性移动使用
    swipe
    ;仅当需要测试 fling 行为时使用
    swipeWithVelocity
    ;仅当需要超过 2 个指针或非线性曲线时使用
    multiTouchSwipe
    。

Verification

验证

  • No occurrence of
    performGesture
    in the test source set:
    git grep -n 'performGesture' src/androidTest src/test
    returns nothing.
  • No
    Thread.sleep
    inside or between
    performTouchInput
    blocks (skydoves hot take #7).
  • No hardcoded
    Offset(<screen-pixel>, <screen-pixel>)
    in the test — every position resolves through
    center
    ,
    top*
    ,
    bottom*
    ,
    centerLeft
    , etc.
  • Assertions following a touch gesture run inside
    rule.runOnIdle { … }
    .
  • ./gradlew :app:connectedDebugAndroidTest
    (or
    :app:testDebugUnitTest
    ) passes for the test under change.
  • 测试源集中不存在
    performGesture
    :
    git grep -n 'performGesture' src/androidTest src/test
    不返回任何结果。
  • performTouchInput
    块内部或块之间不存在
    Thread.sleep
    (skydoves 热门观点 #7)。
  • 测试中不存在硬编码的
    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
    —
    performTouchInput
    (Actions.kt:399),
    performGesture
    deprecation (Actions.kt:337-355).
  • compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/TouchInjectionScope.kt
    — DSL surface (
    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
    — geometry helpers (
    center
    ,
    topLeft
    ,
    topCenter
    ,
    bottomRight
    ,
    width
    ,
    height
    ,
    right
    ,
    bottom
    ,
    percentOffset
    ,
    visibleSize
    ,
    advanceEventTime
    ).
  • compose/foundation/foundation/src/androidDeviceTest/.../DraggableTest.kt
    — canonical
    swipe(start, end, durationMillis)
    (DraggableTest.kt:114-146).
  • compose/foundation/foundation/src/androidDeviceTest/.../TransformableTest.kt
    —
    pinch(...)
    four-point gesture (TransformableTest.kt:128-141).
  • compose/foundation/foundation/src/androidDeviceTest/.../CombinedClickableTest.kt
    —
    performTouchInput { longClick() }
    , split
    down(center)
    /
    up()
    blocks for haptic tests.
  • compose/foundation/foundation/src/androidDeviceTest/.../ScrollableAreaTest.kt
    — low-level
    down(); moveBy()
    flow.
  • 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
    ——
    performTouchInput
    (Actions.kt:399),以及
    performGesture
    弃用说明(Actions.kt:337-355)。
  • compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/TouchInjectionScope.kt
    ——DSL 接口(
    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
    ——标准的
    swipe(start, end, durationMillis)
    (DraggableTest.kt:114-146)。
  • compose/foundation/foundation/src/androidDeviceTest/.../TransformableTest.kt
    ——四点
    pinch(...)
    手势(TransformableTest.kt:128-141)。
  • 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