testing-with-espresso-interop
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTesting with Espresso Interop — One Activity, Two Test Frameworks, One Bridge
使用 Espresso 互操作进行测试——一个 Activity、两个测试框架、一座桥接
The Compose and the Espresso API operate on the same simultaneously. Compose synchronization (idling resources, frame clock awaits) is bridged into Espresso through a single internal named , so the developer does not register anything manually. The trap is threading: MUST run on the test thread, not from inside or . This skill encodes the canonical interop pattern from 's text-field IME tests.
ComposeTestRuleonViewActivityIdlingResourceEspressoLinkEspresso.onViewrule.runOnIdle { }rule.runOnUiThread { }androidx.compose.foundationCompose 与 Espresso API 可同时作用于同一个 。Compose 同步机制(idle resources、frame clock awaits)通过一个名为 的内部 桥接到 Espresso,因此开发者无需手动注册任何内容。线程方面存在一个陷阱: 必须在测试线程上运行,不能在 或 内运行。本 skill 记录了 文本字段 IME 测试中的标准互操作模式。
ComposeTestRuleonViewActivityEspressoLinkIdlingResourceEspresso.onViewrule.runOnIdle { }rule.runOnUiThread { }androidx.compose.foundationWhen to use this skill
何时使用此 skill
- The test must operate on an Android window (which lives in its own
Dialogand may not be in the Compose semantic tree).Window - The test must verify IME (soft keyboard) state — only Espresso's makes the keyboard appear.
onView(supportsInputMethods()).perform(click()) - The screen-under-test is a hybrid with an Android View hierarchy that contains a
Activity, or vice versa.ComposeView - The developer asks "how do I use Espresso and Compose in the same test".
- A test calls from
Espresso.onView(...)and hangs / throws "cannot be run from the main thread".runOnIdle { }
- 测试必须操作 Android 窗口(它位于自己的
Dialog中,可能不在 Compose 语义树中)。Window - 测试必须验证 IME(软键盘)状态——只有 Espresso 的 能让键盘显示出来。
onView(supportsInputMethods()).perform(click()) - 被测屏幕是混合型 ,其 Android View 层级中包含
Activity,或者反过来。ComposeView - 开发者询问“如何在同一个测试中使用 Espresso 和 Compose”。
- 测试从 中调用
runOnIdle { }后挂起,或抛出“cannot be run from the main thread”。Espresso.onView(...)
When NOT to use this skill
何时不应使用此 skill
- The test is pure Compose; no Android View interactions exist. Use .
../../patterns/structuring-a-compose-test/SKILL.md - The synchronization symptom is "test passes locally, flaky on CI" without any View interop. Use .
../../synchronization/synchronizing-with-idle/SKILL.md - The test is for an (Compose dialog) — that DOES surface in the semantics tree via
androidx.compose.ui.window.Dialogand does NOT need Espresso. UseisDialog().../../finders/composing-semantics-matchers/SKILL.md
- 测试是纯 Compose 测试,不存在任何 Android View 交互。请使用 。
../../patterns/structuring-a-compose-test/SKILL.md - 同步问题的表现是“测试在本地通过,但在 CI 上不稳定”,且不存在任何 View 互操作。请使用 。
../../synchronization/synchronizing-with-idle/SKILL.md - 测试针对 (Compose dialog)——它确实会通过
androidx.compose.ui.window.Dialog出现在语义树中,且不需要 Espresso。请使用isDialog()。../../finders/composing-semantics-matchers/SKILL.md
Prerequisites
前置条件
- on
androidx.test.espresso:espresso-core.androidTestImplementation - on
androidx.compose.ui:ui-test-junit4andandroidTestImplementationonandroidx.compose.ui:ui-test-manifest(seedebugImplementation).../../setup/configuring-test-dependencies/SKILL.md - An that hosts both layers —
Activityis the standard pick; a customFragmentActivitydeclared inActivityalso works.src/androidTest/AndroidManifest.xml - The test class skeleton from .
../../patterns/structuring-a-compose-test/SKILL.md
- 在 中添加
androidTestImplementation。androidx.test.espresso:espresso-core - 在 中添加
androidTestImplementation,并在androidx.compose.ui:ui-test-junit4中添加debugImplementation(请参阅androidx.compose.ui:ui-test-manifest)。../../setup/configuring-test-dependencies/SKILL.md - 一个承载两层的 ——
Activity是标准选择;也可以使用在FragmentActivity中声明的自定义src/androidTest/AndroidManifest.xml。Activity - 来自 的测试类骨架。
../../patterns/structuring-a-compose-test/SKILL.md
Workflow
工作流
- 1. Use (v2) for the host Activity. Cited from
createAndroidComposeRule<A>():compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/textfield/TextFieldFocusCustomDialogTest.kt:60
kotlin
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
import androidx.fragment.app.FragmentActivity
import kotlinx.coroutines.test.StandardTestDispatcher
@get:Rule
val rule = createAndroidComposeRule<FragmentActivity>(StandardTestDispatcher())-
2. Set Compose content with, then call
rule.setContent { }. This drains the Compose recomposer/effect queue so the next Espresso interaction sees a stable view tree.rule.waitForIdle() -
3. Drive the View layer from the test thread via. Do NOT wrap this call in
Espresso.onView(...)orrunOnIdle.runOnUiThread
kotlin
import androidx.test.espresso.Espresso
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.matcher.ViewMatchers
rule.waitForIdle()
Espresso.onView(ViewMatchers.supportsInputMethods()).perform(ViewActions.click())Cited from . The full IME test:
TextFieldFocusCustomDialogTest.kt:117-119kotlin
@Test
fun keyboardShown_forFieldInAndroidDialog_…() {
val focusRequester = FocusRequester()
val keyboardHelper = KeyboardHelper(rule)
rule.setContent {
wrapContent {
keyboardHelper.initialize()
LaunchedEffect(Unit) { focusRequester.requestFocus() }
BasicTextField(
value = "",
onValueChange = {},
modifier = Modifier.focusRequester(focusRequester),
)
}
}
rule.waitForIdle()
// The dialog's window must be focused for the IME to actually show.
Espresso.onView(ViewMatchers.supportsInputMethods()).perform(ViewActions.click())
keyboardHelper.waitForKeyboardVisibility(visible = true)
}- 4. Mix Compose and Espresso assertions freely on the test thread. The two APIs run against the same Activity.
kotlin
rule.onNodeWithTag("submit").performClick()
Espresso.onView(ViewMatchers.withId(R.id.legacy_toast)).check(matches(ViewMatchers.isDisplayed()))- 5. (Optional) Scope Compose finders to a sub-tree resolved by Espresso. When the Activity contains multiple Compose hosts and a single Espresso identifies which one to interact with, use
ViewInteraction. This is supported only ononRootWithViewInteraction(viewInteraction); non-Android test rules throwAndroidComposeTestRule."This implementation of ComposeTestRule does not support onRootWithViewInteraction."
kotlin
val nestedComposeView = Espresso.onView(ViewMatchers.withId(R.id.nested_compose))
rule.onRootWithViewInteraction(nestedComposeView).onNodeWithTag("submit").performClick()-
6. Trust thebridge. Compose's
EspressoLinks — recomposer, snapshot, frame clock — are aggregated byIdlingResourceand surfaced to Espresso through a singleComposeIdlingResourcenamedIdlingResource. Cited from"Compose-Espresso link". The framework registers and unregisters it insidecompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.kt:34-84(lines 58-73). The developer does NOT needwithStrategy { }for Compose state.IdlingRegistry.getInstance().register(...) -
7. Conversely, Espresso idling resources are visible to Compose. Anything registered viais awaited by
IdlingRegistry.getInstance().register(…)because the rule polls Espresso through the same bridge.rule.waitForIdle()
- 1. 对宿主 Activity 使用 (v2)。 引用自
createAndroidComposeRule<A>():compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/textfield/TextFieldFocusCustomDialogTest.kt:60
kotlin
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
import androidx.fragment.app.FragmentActivity
import kotlinx.coroutines.test.StandardTestDispatcher
@get:Rule
val rule = createAndroidComposeRule<FragmentActivity>(StandardTestDispatcher())-
2. 通过设置 Compose 内容,然后调用
rule.setContent { }。 这会排空 Compose 的 recomposer/effect 队列,使下一次 Espresso 交互能够看到稳定的 View 树。rule.waitForIdle() -
3. 通过在测试线程上驱动 View 层。 不要将 this 调用包装在
Espresso.onView(...)或runOnIdle中。runOnUiThread
kotlin
import androidx.test.espresso.Espresso
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.matcher.ViewMatchers
rule.waitForIdle()
Espresso.onView(ViewMatchers.supportsInputMethods()).perform(ViewActions.click())引用自 。完整的 IME 测试:
TextFieldFocusCustomDialogTest.kt:117-119kotlin
@Test
fun keyboardShown_forFieldInAndroidDialog_…() {
val focusRequester = FocusRequester()
val keyboardHelper = KeyboardHelper(rule)
rule.setContent {
wrapContent {
keyboardHelper.initialize()
LaunchedEffect(Unit) { focusRequester.requestFocus() }
BasicTextField(
value = "",
onValueChange = {},
modifier = Modifier.focusRequester(focusRequester),
)
}
}
rule.waitForIdle()
// The dialog's window must be focused for the IME to actually show.
Espresso.onView(ViewMatchers.supportsInputMethods()).perform(ViewActions.click())
keyboardHelper.waitForKeyboardVisibility(visible = true)
}- 4. 在测试线程上自由混合使用 Compose 和 Espresso 断言。 两个 API 会作用于同一个 Activity。
kotlin
rule.onNodeWithTag("submit").performClick()
Espresso.onView(ViewMatchers.withId(R.id.legacy_toast)).check(matches(ViewMatchers.isDisplayed()))- 5.(可选)将 Compose finder 限定到由 Espresso 解析出的子树。 当 Activity 包含多个 Compose host,且单个 Espresso 可用于确定要与哪个 host 交互时,使用
ViewInteraction。此 API 仅在onRootWithViewInteraction(viewInteraction)上受支持;非 Android test rule 会抛出AndroidComposeTestRule。This implementation of ComposeTestRule does not support onRootWithViewInteraction.
kotlin
val nestedComposeView = Espresso.onView(ViewMatchers.withId(R.id.nested_compose))
rule.onRootWithViewInteraction(nestedComposeView).onNodeWithTag("submit").performClick()-
6. 信任桥接机制。 Compose 的
EspressoLink——recomposer、snapshot、frame clock——由IdlingResource聚合,并通过一个名为ComposeIdlingResource的Compose-Espresso link暴露给 Espresso。引用自IdlingResource。框架会在compose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.kt:34-84内注册和注销它(第 58-73 行)。开发者不需要为 Compose 状态调用withStrategy { }。IdlingRegistry.getInstance().register(...) -
7. 反过来,Espresso idle resources 对 Compose 可见。 通过注册的任何内容都会被
IdlingRegistry.getInstance().register(…)等待,因为该 rule 会通过同一桥接机制轮询 Espresso。rule.waitForIdle()
Patterns
模式
Pattern: Espresso.onView
from runOnIdle
deadlocks
Espresso.onViewrunOnIdle模式:在 runOnIdle
中调用 Espresso.onView
导致死锁
runOnIdleEspresso.onViewkotlin
// WRONG
@Test
fun submit() {
rule.setContent { /* Compose UI with a button that opens a Dialog */ }
rule.onNodeWithTag("open").performClick()
rule.runOnIdle {
Espresso.onView(ViewMatchers.withId(R.id.confirm)).perform(ViewActions.click())
}
}
// WRONG because: runOnIdle posts to the UI thread. Espresso.onView calls Espresso.onIdle()
// internally, and EspressoLink.runUntilIdle (EspressoLink.android.kt:75-83) explicitly
// throws on UI-thread invocations:
// "Functions that involve synchronization (Assertions, Actions, Synchronization;
// e.g. assertIsSelected(), doClick(), runOnIdle()) cannot be run from the main thread.
// Did you nest such a function inside runOnIdle {}, runOnUiThread {} or setContent {}?"kotlin
// RIGHT
@Test
fun submit() {
rule.setContent { /* Compose UI with a button that opens a Dialog */ }
rule.onNodeWithTag("open").performClick()
rule.waitForIdle()
Espresso.onView(ViewMatchers.withId(R.id.confirm)).perform(ViewActions.click())
}kotlin
// WRONG
@Test
fun submit() {
rule.setContent { /* Compose UI with a button that opens a Dialog */ }
rule.onNodeWithTag("open").performClick()
rule.runOnIdle {
Espresso.onView(ViewMatchers.withId(R.id.confirm)).perform(ViewActions.click())
}
}
// WRONG because: runOnIdle posts to the UI thread. Espresso.onView calls Espresso.onIdle()
// internally, and EspressoLink.runUntilIdle (EspressoLink.android.kt:75-83) explicitly
// throws on UI-thread invocations:
// "Functions that involve synchronization (Assertions, Actions, Synchronization;
// e.g. assertIsSelected(), doClick(), runOnIdle()) cannot be run from the main thread.
// Did you nest such a function inside runOnIdle {}, runOnUiThread {} or setContent {}?"kotlin
// RIGHT
@Test
fun submit() {
rule.setContent { /* Compose UI with a button that opens a Dialog */ }
rule.onNodeWithTag("open").performClick()
rule.waitForIdle()
Espresso.onView(ViewMatchers.withId(R.id.confirm)).perform(ViewActions.click())
}Pattern: dialog focus via Espresso, content via Compose
模式:通过 Espresso 处理 Dialog 焦点,通过 Compose 处理内容
kotlin
// WRONG — assuming Compose's IME helper alone is enough
@Test
fun dialogKeyboard() {
rule.setContent { CustomDialog { BasicTextField(/* … */) } }
keyboardHelper.waitForKeyboardVisibility(visible = true) // never visible
}
// WRONG because: Android Dialogs live in a separate Window. Even if the TextField requests
// focus, the soft keyboard does not appear until the dialog window itself takes input
// focus. Only Espresso can drive that — `onView(supportsInputMethods()).perform(click())`.kotlin
// RIGHT
@Test
fun dialogKeyboard() {
rule.setContent { CustomDialog { BasicTextField(/* … */) } }
rule.waitForIdle()
Espresso.onView(ViewMatchers.supportsInputMethods()).perform(ViewActions.click())
keyboardHelper.waitForKeyboardVisibility(visible = true)
}kotlin
// WRONG — assuming Compose's IME helper alone is enough
@Test
fun dialogKeyboard() {
rule.setContent { CustomDialog { BasicTextField(/* … */) } }
keyboardHelper.waitForKeyboardVisibility(visible = true) // never visible
}
// WRONG because: Android Dialogs live in a separate Window. Even if the TextField requests
// focus, the soft keyboard does not appear until the dialog window itself takes input
// focus. Only Espresso can drive that — `onView(supportsInputMethods()).perform(click())`.kotlin
// RIGHT
@Test
fun dialogKeyboard() {
rule.setContent { CustomDialog { BasicTextField(/* … */) } }
rule.waitForIdle()
Espresso.onView(ViewMatchers.supportsInputMethods()).perform(ViewActions.click())
keyboardHelper.waitForKeyboardVisibility(visible = true)
}Pattern: createComposeRule()
cannot reach an Activity
createComposeRule()模式:createComposeRule()
无法访问 Activity
createComposeRule()kotlin
// WRONG
@get:Rule val rule = createComposeRule(StandardTestDispatcher()) // ComponentActivity host
@Test fun customActivityFlow() {
Espresso.onView(ViewMatchers.withId(R.id.my_activity_view)) // does not exist
.perform(ViewActions.click())
}
// WRONG because: createComposeRule launches the empty ComponentActivity from ui-test-manifest.
// To interact with a custom Activity's view hierarchy, launch that Activity via
// createAndroidComposeRule<MyActivity>().kotlin
// RIGHT
@get:Rule val rule = createAndroidComposeRule<MyActivity>(StandardTestDispatcher())kotlin
// WRONG
@get:Rule val rule = createComposeRule(StandardTestDispatcher()) // ComponentActivity host
@Test fun customActivityFlow() {
Espresso.onView(ViewMatchers.withId(R.id.my_activity_view)) // does not exist
.perform(ViewActions.click())
}
// WRONG because: createComposeRule launches the empty ComponentActivity from ui-test-manifest.
// To interact with a custom Activity's view hierarchy, launch that Activity via
// createAndroidComposeRule<MyActivity>().kotlin
// RIGHT
@get:Rule val rule = createAndroidComposeRule<MyActivity>(StandardTestDispatcher())Mandatory rules
强制规则
- MUST call from the test thread, AFTER
Espresso.onView(...). MUST NOT wrap it inrule.waitForIdle()orrule.runOnIdle { }— Espresso's idle wait throws on the UI thread (rule.runOnUiThread { }).EspressoLink.android.kt:75-83 - MUST use for any test that needs to address View IDs of the host Activity.
createAndroidComposeRule<A>(StandardTestDispatcher())only launches the barecreateComposeRule()fromComponentActivity.ui-test-manifest - MUST NOT manually register a Compose with
IdlingResource—IdlingRegistry.getInstance()(a single bridge resource namedEspressoLink) does this for the framework. Cited at"Compose-Espresso link".EspressoLink.android.kt:34-84 - PREFERRED: scope Compose interactions to a Compose subtree via when an Activity hosts multiple
rule.onRootWithViewInteraction(viewInteraction)s. Calling it on a non-ComposeViewimplementation throwsAndroidComposeTestRule(the source usesIllegalStateExceptionaterror("This implementation of ComposeTestRule does not support onRootWithViewInteraction.")).ComposeTestRuleExt.android.kt:38-42 - PREFERRED: for soft-keyboard tests, follow →
rule.setContent { … }→rule.waitForIdle()→Espresso.onView(supportsInputMethods()).perform(click())(keyboardHelper.waitForKeyboardVisibility(visible = true)).TextFieldFocusCustomDialogTest.kt:117-128 - MUST NOT use this skill for (Compose dialog) — those surface as semantic nodes matched by
androidx.compose.ui.window.Dialog. SeeisDialog().../../finders/composing-semantics-matchers/SKILL.md
- 必须在测试线程上、之后调用
rule.waitForIdle()。不得将其包装在Espresso.onView(...)或rule.runOnIdle { }中——Espresso 的 idle wait 会在 UI 线程上抛出异常(rule.runOnUiThread { })。EspressoLink.android.kt:75-83 - 必须对任何需要访问宿主 Activity 的 View ID 的测试使用 。
createAndroidComposeRule<A>(StandardTestDispatcher())只会启动createComposeRule()中裸的ui-test-manifest。ComponentActivity - 不得使用 手动注册 Compose
IdlingRegistry.getInstance()——框架已通过IdlingResource(一个名为EspressoLink的桥接资源)完成此操作。引用自Compose-Espresso link。EspressoLink.android.kt:34-84 - **推荐:**当一个 Activity 承载多个 时,通过
ComposeView将 Compose 交互限定到 Compose 子树。对非rule.onRootWithViewInteraction(viewInteraction)实现调用它会抛出AndroidComposeTestRule(源码在IllegalStateException使用ComposeTestRuleExt.android.kt:38-42)。error("This implementation of ComposeTestRule does not support onRootWithViewInteraction.") - **推荐:**对于软键盘测试,请遵循 →
rule.setContent { … }→rule.waitForIdle()→Espresso.onView(supportsInputMethods()).perform(click())的流程(keyboardHelper.waitForKeyboardVisibility(visible = true))。TextFieldFocusCustomDialogTest.kt:117-128 - 不得将此 skill 用于 (Compose dialog)——它们会作为可由
androidx.compose.ui.window.Dialog匹配的语义节点出现。请参阅isDialog()。../../finders/composing-semantics-matchers/SKILL.md
Verification
验证
- The rule is — not
createAndroidComposeRule<HostActivity>(StandardTestDispatcher()).createComposeRule() - Every call lives at test-method scope, not inside
Espresso.onView(...)/runOnIdle { }/runOnUiThread { }.setContent { } - is called between the Compose action and the next
rule.waitForIdle()(or vice versa).Espresso.onView(...) - No manual calls appear — the framework does this through
IdlingRegistry.getInstance().register(composeIdlingResource).EspressoLink - When multiple s exist in one Activity, finders are scoped via
ComposeView.rule.onRootWithViewInteraction(...) - No is used to "let Espresso settle" —
Thread.sleepalready polls Espresso through the bridge. Seerule.waitForIdle().../../synchronization/synchronizing-with-idle/SKILL.md
- 使用的规则是 ,而不是
createAndroidComposeRule<HostActivity>(StandardTestDispatcher())。createComposeRule() - 每个 调用都位于测试方法作用域内,而不是
Espresso.onView(...)/runOnIdle { }/runOnUiThread { }内部。setContent { } - 在 Compose 操作与下一次 之间调用了
Espresso.onView(...)(或反之亦然)。rule.waitForIdle() - 没有手动调用 ——框架已通过
IdlingRegistry.getInstance().register(composeIdlingResource)完成此操作。EspressoLink - 当一个 Activity 中存在多个 时,通过
ComposeView限定 finder 范围。rule.onRootWithViewInteraction(...) - 没有使用 来“让 Espresso 稳定”——
Thread.sleep已通过桥接机制轮询 Espresso。请参阅rule.waitForIdle()。../../synchronization/synchronizing-with-idle/SKILL.md
References
参考资料
- Espresso onView API: https://developer.android.com/training/testing/espresso/basics
- Compose-Espresso interop guide: https://developer.android.com/develop/ui/compose/testing#interop-uiautomator-espresso
- IME interop canonical test:
compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/textfield/TextFieldFocusCustomDialogTest.kt:57-128 - bridge implementation:
EspressoLinkcompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.kt:34-84 - definition:
onRootWithViewInteractioncompose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/AndroidComposeTestRule.android.kt - v2:
createAndroidComposeRulecompose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/v2/AndroidComposeTestRule.android.kt - KeyboardHelper utility:
compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/text/KeyboardHelper.kt
- Espresso API:https://developer.android.com/training/testing/espresso/basics
onView - Compose-Espresso 互操作指南:https://developer.android.com/develop/ui/compose/testing#interop-uiautomator-espresso
- IME 互操作标准测试:
compose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/textfield/TextFieldFocusCustomDialogTest.kt:57-128 - 桥接实现:
EspressoLinkcompose/ui/ui-test/src/androidMain/kotlin/androidx/compose/ui/test/EspressoLink.android.kt:34-84 - 定义:
onRootWithViewInteractioncompose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/AndroidComposeTestRule.android.kt - v2:
createAndroidComposeRulecompose/ui/ui-test-junit4/src/androidMain/kotlin/androidx/compose/ui/test/junit4/v2/AndroidComposeTestRule.android.kt - 工具:
KeyboardHelpercompose/foundation/foundation/src/androidDeviceTest/kotlin/androidx/compose/foundation/text/KeyboardHelper.kt