writing-espresso-tests
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWriting Espresso Tests — The Idle-Then-Act Model for Android Views
编写 Espresso 测试——面向 Android Views 的“先空闲、再操作”模型
Espresso is the canonical instrumentation-time UI test framework for Android Views (not Compose — for Compose, use the skill set; for cross-Compose-View interop see ). Each call internally pumps the main looper to idle, finds exactly one matching view, runs the action, and pumps to idle again before checking. This skill encodes the full matcher/action/assertion catalog, the trap, and the per-version gotchas.
compose/../../../compose/interop/testing-with-espresso-interop/SKILL.mdonView(...).perform(...).check(...)RootMatchers.DEFAULTEspresso 是 Android Views 在插桩测试阶段进行 UI 测试的标准框架(不适用于 Compose——对于 Compose,请使用 skill 集;关于 Compose 与 View 的跨框架互操作,请参阅 )。每个 调用都会在内部将主 Looper 泵送至空闲,查找恰好一个匹配的 View,执行操作,并在检查前再次泵送至空闲。此 skill 涵盖完整的 matcher/action/assertion 目录、 陷阱以及各版本特有的注意事项。
compose/../../../compose/interop/testing-with-espresso-interop/SKILL.mdonView(...).perform(...).check(...)RootMatchers.DEFAULTWhen to use this skill
何时使用此 skill
- The user is testing an Activity, Fragment, or Dialog whose UI is built with Android Views (XML layouts, AppCompat, Material View components).
- A test fails with ,
NoMatchingViewException, orAmbiguousViewMatcherException.PerformException - A click on an button silently does nothing —
AlertDialogexcludes dialogs.RootMatchers.DEFAULT - The user wants to stub for camera, contacts, or share flows.
Intent.startActivityForResult - The user wants to register an for a long-running task that Espresso can't see.
IdlingResource - The user is debugging a interaction.
RecyclerView - The user mentions and is surprised it isn't on the classpath in Espresso 3.7.0 contrib.
BottomNavigationViewActions
- 用户正在测试 UI 由 Android Views(XML 布局、AppCompat、Material View 组件)构建的 Activity、Fragment 或 Dialog。
- 测试因 、
NoMatchingViewException或AmbiguousViewMatcherException而失败。PerformException - 点击 按钮后没有任何效果——
AlertDialog会排除对话框。RootMatchers.DEFAULT - 用户希望为相机、联系人或分享流程 stub 。
Intent.startActivityForResult - 用户希望为 Espresso 无法感知的长时间运行任务注册 。
IdlingResource - 用户正在调试 交互。
RecyclerView - 用户提到 ,并对其未出现在 Espresso 3.7.0 contrib 的 classpath 中感到意外。
BottomNavigationViewActions
When NOT to use this skill
何时不应使用此 skill
- The UI is Jetpack Compose — use skills (
compose/, etc.). Mixed Compose+View hosts:../../../compose/finders/finding-nodes-by-tag-text-content/SKILL.md.../../../compose/interop/testing-with-espresso-interop/SKILL.md - The test crosses app boundaries (Settings, dialer, system UI) — from Espresso. Use
InjectEventSecurityException.../../uiautomator/cross-app-tests-with-uiautomator/SKILL.md - The runner stack is not yet set up — start with .
../../runner/running-instrumented-tests-with-androidjunit4/SKILL.md - The Activity has not been launched — pair with .
../../scenarios/launching-activities-with-activityscenario/SKILL.md
- UI 是 Jetpack Compose——请使用 skills(
compose/等)。对于混合 Compose+View 宿主,请使用../../../compose/finders/finding-nodes-by-tag-text-content/SKILL.md。../../../compose/interop/testing-with-espresso-interop/SKILL.md - 测试跨越应用边界(Settings、dialer、system UI)——Espresso 会抛出 。请改用
InjectEventSecurityException。../../uiautomator/cross-app-tests-with-uiautomator/SKILL.md - Runner stack 尚未配置——请先阅读 。
../../runner/running-instrumented-tests-with-androidjunit4/SKILL.md - Activity 尚未启动——请配合 使用。
../../scenarios/launching-activities-with-activityscenario/SKILL.md
Prerequisites
前置条件
- Runner stack from .
../../runner/running-instrumented-tests-with-androidjunit4/SKILL.md - Espresso artifacts (3.7.0 GA per H.1):
docs/CORPUS.md
kotlin
dependencies {
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
androidTestImplementation("androidx.test.espresso:espresso-contrib:3.7.0") // RecyclerViewActions, PickerActions
androidTestImplementation("androidx.test.espresso:espresso-intents:3.7.0") // Intents.intended/intending
androidTestImplementation("androidx.test.espresso:espresso-accessibility:3.7.0")
androidTestImplementation("androidx.test.espresso:espresso-web:3.7.0") // WebView
implementation("androidx.test.espresso:espresso-idling-resource:3.7.0") // for production code that exposes IdlingResources
}
android.testOptions.animationsDisabled = true // hermetic- An (or Fragment) launched via
Activity/ActivityScenario/ActivityScenarioRule.FragmentScenario
- 来自 的 Runner stack。
../../runner/running-instrumented-tests-with-androidjunit4/SKILL.md - Espresso 依赖项(根据 H.1,版本为 3.7.0 GA):
docs/CORPUS.md
kotlin
dependencies {
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
androidTestImplementation("androidx.test.espresso:espresso-contrib:3.7.0") // RecyclerViewActions, PickerActions
androidTestImplementation("androidx.test.espresso:espresso-intents:3.7.0") // Intents.intended/intending
androidTestImplementation("androidx.test.espresso:espresso-accessibility:3.7.0")
androidTestImplementation("androidx.test.espresso:espresso-web:3.7.0") // WebView
implementation("androidx.test.espresso:espresso-idling-resource:3.7.0") // for production code that exposes IdlingResources
}
android.testOptions.animationsDisabled = true // hermetic- 通过 /
ActivityScenario/ActivityScenarioRule启动的 Activity(或 Fragment)。FragmentScenario
Workflow
工作流
- 1. Find views with . The matcher is a Hamcrest
onView(matcher). Identity-first matchers (most preferred):Matcher<View>,withId(R.id.button),withTagKey(int). Text/desc fallback:withResourceName(String),withText,withContentDescription. Source:withHint(lines 79-1000+, R3 lines 180-280):androidx.test.espresso.matcher.ViewMatchers
kotlin
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.matcher.ViewMatchers.*
import org.hamcrest.Matchers.allOf
onView(withId(R.id.submit_button))
onView(allOf(withText("Submit"), isEnabled()))
onView(withContentDescription("Open menu"))
onView(allOf(withId(R.id.subtitle), hasDescendant(withText("Hello"))))-
2. Compose state-aware matchers. Common state matchers from:
ViewMatchers,isDisplayed,isCompletelyDisplayed,isDisplayingAtLeast(percent)/isEnabled,isNotEnabled,isFocused/isChecked,isNotChecked,isSelected,withEffectiveVisibility(Visibility.VISIBLE|INVISIBLE|GONE). Hierarchy matchers:withAlpha(float),withParent,hasDescendant,withChild,isRoot,withClassName. Layout-relative:isAssignableFrom(Class),hasSibling. Source: R3 lines 180-280.isDescendantOfA -
3. Act withvia
ViewActions. From.perform(action):androidx.test.espresso.action.ViewActions
kotlin
import androidx.test.espresso.action.ViewActions.*
onView(withId(R.id.email)).perform(typeText("test@example.com"), closeSoftKeyboard())
onView(withId(R.id.submit_button)).perform(click())
onView(withId(R.id.input)).perform(replaceText("new"), pressImeActionButton())
onView(withId(R.id.list)).perform(swipeUp())
onView(withId(R.id.scroller)).perform(scrollTo()) // requires single-direction ScrollViewClick family: , , . Text: , , , , , . Gesture: , , , , . Source: .
clicklongClickdoubleClicktypeTextreplaceTextclearTextpressKeypressImeActionButtoncloseSoftKeyboardswipeUpswipeDownswipeLeftswipeRightscrollToandroidx.test.espresso.action.ViewActions- 4. Assert with via
ViewAssertions. From.check(...):androidx.test.espresso.assertion.ViewAssertions
kotlin
import androidx.test.espresso.assertion.ViewAssertions.*
import androidx.test.espresso.matcher.ViewMatchers.*
onView(withId(R.id.title)).check(matches(withText("Welcome")))
onView(withId(R.id.banner)).check(matches(isDisplayed()))
onView(withId(R.id.banner)).check(doesNotExist())
onView(withId(R.id.list)).check(selectedDescendantsMatch(withId(R.id.row), isCompletelyDisplayed()))matches(matcher)doesNotExist()matches(not(isDisplayed()))- 5. Recognize the implicit idle. Every and
onView(...).perform(...)call internally:.check(...)- Submits the action on the main thread via the dagger-injected .
mainThreadExecutor - Calls until: the main
uiController.loopMainThreadUntilIdle()is empty, allMessageQueues registered withIdlingResourcereportIdlingRegistry, all registered non-mainisIdleNow == trues are idle, and the AsyncTask thread pool is idle.Looper - Resolves the view (against the current
viewMatcher's hierarchy). 0 →Root; 2+ →NoMatchingViewException.AmbiguousViewMatcherException - Checks → throws
viewAction.getConstraints().matches(view)if false.PerformException - Calls (or
viewAction.perform(uiController, view)).viewAssertion.check(view, null) - Loops the main thread to idle again before returning.
- Submits the action on the main thread via the dagger-injected
This is the idle-then-act model. Tests that work locally but fail on CI are usually missing an for a non-Looper-driven async path (custom , OkHttp's dispatcher, etc.). Source: R3 lines 165-178, 811-820.
IdlingResourceExecutorService- 6. For dialogs and popups, override the root with .
inRoot(...)excludes dialogs, popups, and toasts (it matches "the focused activity window"). For anRootMatchers.DEFAULTbutton:AlertDialog
kotlin
import androidx.test.espresso.matcher.RootMatchers.*
onView(withText("Submit")).inRoot(isDialog()).perform(click())
onView(withText("Copy")).inRoot(isPlatformPopup()).perform(click()) // overflow menu, popup window
onView(withText("Saved")).inRoot(isPlatformPopup()).check(matches(isDisplayed())) // toastRootMatchers.DEFAULTallOf(hasWindowLayoutParams(), allOf(anyOf(allOf(isDialog(), withDecorView(hasWindowFocus())), isSubwindowOfCurrentActivity()), isFocusable()))- 7. For , use
RecyclerViewfrom contrib.RecyclerViewActionsagainst aonView(...).perform(...)'s row directly does NOT work because the row may be off-screen (no view to find):RecyclerView
kotlin
import androidx.test.espresso.contrib.RecyclerViewActions.*
onView(withId(R.id.list))
.perform(scrollToPosition<RecyclerView.ViewHolder>(20))
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(3, click()))
onView(withId(R.id.list))
.perform(scrollTo<RecyclerView.ViewHolder>(hasDescendant(withText("Pikachu"))))
onView(withId(R.id.list))
.perform(actionOnItem<RecyclerView.ViewHolder>(hasDescendant(withText("Pikachu")), click()))All require constraint (R3 line 428).
RecyclerViewActionsisAssignableFrom(RecyclerView.class) AND isDisplayed()- 8. For (ListView, Spinner), use
AdapterViewnotonData(...).onView(...)
kotlin
import androidx.test.espresso.Espresso.onData
import org.hamcrest.Matchers.allOf
onData(allOf(`is`(instanceOf(String::class.java)), `is`("Item 5")))
.inAdapterView(withId(R.id.list))
.perform(click())onData- 9. Stub and verify intents with . Init in
Intents, release in@Before. The@After(3.5+) handles both:IntentsRule
kotlin
import androidx.test.espresso.intent.rule.IntentsRule
import androidx.test.espresso.intent.Intents.*
import androidx.test.espresso.intent.matcher.IntentMatchers.*
@get:Rule val intentsRule = IntentsRule()
@Test
fun openCameraStub() {
intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE))
.respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, Intent()))
onView(withId(R.id.take_photo)).perform(click())
intended(allOf(
hasAction(MediaStore.ACTION_IMAGE_CAPTURE),
hasFlag(Intent.FLAG_GRANT_READ_URI_PERMISSION),
))
}IntentsTestRule@Deprecateddocs/CORPUS.mdIntentsRuleIntents.init()Intents.release()- 10. Register for non-Looper async work. Espresso watches the main looper and the
IdlingResourcepool by default; for OkHttp, customAsyncTask, or sensor pipelines you must surface idleness:ExecutorService
kotlin
class CountingIdlingResource(private val name: String) : IdlingResource {
private val counter = AtomicInteger(0)
private var callback: IdlingResource.ResourceCallback? = null
override fun getName() = name
override fun isIdleNow() = counter.get() == 0
override fun registerIdleTransitionCallback(cb: IdlingResource.ResourceCallback) { callback = cb }
fun increment() { counter.incrementAndGet() }
fun decrement() { if (counter.decrementAndGet() == 0) callback?.onTransitionToIdle() }
}
@Before fun setUp() = IdlingRegistry.getInstance().register(myIdler)
@After fun tearDown() = IdlingRegistry.getInstance().unregister(myIdler)
// Master policy default is 60 seconds; setIdlingResourceTimeout default is 26 seconds.
// For debugger sessions, opt out of timeouts entirely with
// IdlingPolicies.setMasterPolicyTimeoutWhenDebuggerAttached(false)
// — there is no "-1 = infinite" magic value.
IdlingPolicies.setMasterPolicyTimeout(60, TimeUnit.SECONDS)
IdlingPolicies.setIdlingResourceTimeout(45, TimeUnit.SECONDS)Wrap network calls / async work in / from production code (the artifact is on , not ).
increment()decrement():espresso-idling-resourceimplementationandroidTestImplementation-
11. Read errors precisely.
- — the matcher resolved zero views in the current root. Confirm the view is currently displayed; if it is in a dialog, add
NoMatchingViewException..inRoot(isDialog()) - — 2+ views matched. Tighten with
AmbiguousViewMatcherException.allOf(...) - — the action's constraint failed (e.g.
PerformExceptionrequiresclick()). The exception message includes the constraint description.isDisplayingAtLeast(90) - — an event would cross to a foreign window. The test reached system UI. Use UiAutomator instead.
InjectEventSecurityException
- 1. 使用 查找 View。 matcher 是 Hamcrest
onView(matcher)。优先使用标识类 matcher(通常最为推荐):Matcher<View>、withId(R.id.button)、withTagKey(int)。文本或描述匹配作为回退方案:withResourceName(String)、withText、withContentDescription。来源:withHint(第 79-1000+ 行,R3 第 180-280 行):androidx.test.espresso.matcher.ViewMatchers
kotlin
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.matcher.ViewMatchers.*
import org.hamcrest.Matchers.allOf
onView(withId(R.id.submit_button))
onView(allOf(withText("Submit"), isEnabled()))
onView(withContentDescription("Open menu"))
onView(allOf(withId(R.id.subtitle), hasDescendant(withText("Hello"))))-
2. 编写状态感知 matcher。中的常见状态 matcher:
ViewMatchers、isDisplayed、isCompletelyDisplayed、isDisplayingAtLeast(percent)/isEnabled、isNotEnabled、isFocused/isChecked、isNotChecked、isSelected、withEffectiveVisibility(Visibility.VISIBLE|INVISIBLE|GONE)。层级 matcher:withAlpha(float)、withParent、hasDescendant、withChild、isRoot、withClassName。布局相对 matcher:isAssignableFrom(Class)、hasSibling。来源:R3 第 180-280 行。isDescendantOfA -
3. 通过使用
.perform(action)执行操作。 来源:ViewActions:androidx.test.espresso.action.ViewActions
kotlin
import androidx.test.espresso.action.ViewActions.*
onView(withId(R.id.email)).perform(typeText("test@example.com"), closeSoftKeyboard())
onView(withId(R.id.submit_button)).perform(click())
onView(withId(R.id.input)).perform(replaceText("new"), pressImeActionButton())
onView(withId(R.id.list)).perform(swipeUp())
onView(withId(R.id.scroller)).perform(scrollTo()) // requires single-direction ScrollView点击系列:、、。文本:、、、、、。手势:、、、、。来源:。
clicklongClickdoubleClicktypeTextreplaceTextclearTextpressKeypressImeActionButtoncloseSoftKeyboardswipeUpswipeDownswipeLeftswipeRightscrollToandroidx.test.espresso.action.ViewActions- 4. 通过 使用
.check(...)进行断言。 来源:ViewAssertions:androidx.test.espresso.assertion.ViewAssertions
kotlin
import androidx.test.espresso.assertion.ViewAssertions.*
import androidx.test.espresso.matcher.ViewMatchers.*
onView(withId(R.id.title)).check(matches(withText("Welcome")))
onView(withId(R.id.banner)).check(matches(isDisplayed()))
onView(withId(R.id.banner)).check(doesNotExist())
onView(withId(R.id.list)).check(selectedDescendantsMatch(withId(R.id.row), isCompletelyDisplayed()))matches(matcher)doesNotExist()matches(not(isDisplayed()))- 5. 识别隐式空闲。 每个 和
onView(...).perform(...)调用都会在内部执行以下操作:.check(...)- 通过 dagger 注入的 在主线程上提交 action。
mainThreadExecutor - 持续调用 ,直到满足以下条件:主
uiController.loopMainThreadUntilIdle()为空、注册到MessageQueue的所有IdlingRegistry都报告IdlingResource、所有已注册的非主isIdleNow == true均处于空闲状态,且 AsyncTask 线程池空闲。Looper - 针对当前 的层级解析 View(使用
Root)。解析到 0 个 →viewMatcher;解析到 2 个或更多 →NoMatchingViewException。AmbiguousViewMatcherException - 检查 → 如果结果为 false,则抛出
viewAction.getConstraints().matches(view)。PerformException - 调用 (或
viewAction.perform(uiController, view))。viewAssertion.check(view, null) - 返回前再次将主线程循环泵送至空闲。
- 通过 dagger 注入的
这就是先空闲、再操作模型。本地运行通过但在 CI 上失败的测试,通常是因为非 Looper 驱动的异步路径(自定义 、OkHttp dispatcher 等)缺少 。来源:R3 第 165-178、811-820 行。
ExecutorServiceIdlingResource- 6. 对于对话框和弹窗,使用 覆盖 root。
inRoot(...)会排除对话框、弹窗和 toast(它匹配“获得焦点的 Activity 窗口”)。对于RootMatchers.DEFAULT按钮:AlertDialog
kotlin
import androidx.test.espresso.matcher.RootMatchers.*
onView(withText("Submit")).inRoot(isDialog()).perform(click())
onView(withText("Copy")).inRoot(isPlatformPopup()).perform(click()) // overflow menu, popup window
onView(withText("Saved")).inRoot(isPlatformPopup()).check(matches(isDisplayed())) // toast根据 R3 第 311 行, 的定义为 ——因此,对通用对话框按钮的点击会悄无声息地找不到目标。
RootMatchers.DEFAULTallOf(hasWindowLayoutParams(), allOf(anyOf(allOf(isDialog(), withDecorView(hasWindowFocus())), isSubwindowOfCurrentActivity()), isFocusable()))- 7. 对于 ,使用 contrib 中的
RecyclerView。 直接对RecyclerViewActions中的行执行RecyclerView不起作用,因为该行可能位于屏幕之外(没有可供查找的 View):onView(...).perform(...)
kotlin
import androidx.test.espresso.contrib.RecyclerViewActions.*
onView(withId(R.id.list))
.perform(scrollToPosition<RecyclerView.ViewHolder>(20))
onView(withId(R.id.list))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(3, click()))
onView(withId(R.id.list))
.perform(scrollTo<RecyclerView.ViewHolder>(hasDescendant(withText("Pikachu"))))
onView(withId(R.id.list))
.perform(actionOnItem<RecyclerView.ViewHolder>(hasDescendant(withText("Pikachu")), click()))所有 都要求满足 constraint(R3 第 428 行)。
RecyclerViewActionsisAssignableFrom(RecyclerView.class) AND isDisplayed()- 8. 对于 (ListView、Spinner),使用
AdapterView而非onData(...)。onView(...)
kotlin
import androidx.test.espresso.Espresso.onData
import org.hamcrest.Matchers.allOf
onData(allOf(\`is\`(instanceOf(String::class.java)), \`is\`("Item 5")))
.inAdapterView(withId(R.id.list))
.perform(click())onData- 9. 使用 stub 和验证 intent。 在
Intents中初始化,在@Before中释放。@After(3.5+)可以同时处理这两项:IntentsRule
kotlin
import androidx.test.espresso.intent.rule.IntentsRule
import androidx.test.espresso.intent.Intents.*
import androidx.test.espresso.intent.matcher.IntentMatchers.*
@get:Rule val intentsRule = IntentsRule()
@Test
fun openCameraStub() {
intending(hasAction(MediaStore.ACTION_IMAGE_CAPTURE))
.respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, Intent()))
onView(withId(R.id.take_photo)).perform(click())
intended(allOf(
hasAction(MediaStore.ACTION_IMAGE_CAPTURE),
hasFlag(Intent.FLAG_GRANT_READ_URI_PERMISSION),
))
}根据 H.7, 已标记为 ——请使用 ,或手动调用 / 。
docs/CORPUS.mdIntentsTestRule@DeprecatedIntentsRuleIntents.init()Intents.release()- 10. 为非 Looper 驱动的异步工作注册 。 默认情况下,Espresso 会监控主 Looper 和 AsyncTask 线程池;但对于 OkHttp、自定义
IdlingResource或传感器管道,你必须显式暴露空闲状态:ExecutorService
kotlin
class CountingIdlingResource(private val name: String) : IdlingResource {
private val counter = AtomicInteger(0)
private var callback: IdlingResource.ResourceCallback? = null
override fun getName() = name
override fun isIdleNow() = counter.get() == 0
override fun registerIdleTransitionCallback(cb: IdlingResource.ResourceCallback) { callback = cb }
fun increment() { counter.incrementAndGet() }
fun decrement() { if (counter.decrementAndGet() == 0) callback?.onTransitionToIdle() }
}
@Before fun setUp() = IdlingRegistry.getInstance().register(myIdler)
@After fun tearDown() = IdlingRegistry.getInstance().unregister(myIdler)
// Master policy default is 60 seconds; setIdlingResourceTimeout default is 26 seconds.
// For debugger sessions, opt out of timeouts entirely with
// IdlingPolicies.setMasterPolicyTimeoutWhenDebuggerAttached(false)
// — there is no "-1 = infinite" magic value.
IdlingPolicies.setMasterPolicyTimeout(60, TimeUnit.SECONDS)
IdlingPolicies.setIdlingResourceTimeout(45, TimeUnit.SECONDS)请在生产代码中用 / 包裹网络调用或异步工作( artifact 应放在 ,而不是 )。
increment()decrement():espresso-idling-resourceimplementationandroidTestImplementation-
11. 准确解读错误。
- ——matcher 在当前 root 中解析出零个 View。确认该 View 当前是否已显示;如果它位于对话框中,请添加
NoMatchingViewException。.inRoot(isDialog()) - ——有两个或更多 View 匹配。请使用
AmbiguousViewMatcherException收紧条件。allOf(...) - ——action 的 constraint 失败(例如,
PerformException要求click())。异常消息中包含 constraint 的描述。isDisplayingAtLeast(90) - ——事件将跨越边界进入外部窗口,说明测试已到达 system UI。请改用 UiAutomator。
InjectEventSecurityException
Patterns
模式
Pattern: WRONG vs RIGHT — clicking a dialog button
模式:错误与正确——点击对话框按钮
kotlin
// WRONG
onView(withText("Submit")).perform(click())
// WRONG because: RootMatchers.DEFAULT (line 51 of RootMatchers.java) excludes dialogs.
// The matcher does not see the dialog window. Result: NoMatchingViewException ("No views in
// hierarchy found matching: with text Submit"), even though the dialog is clearly on screen.kotlin
// RIGHT
import androidx.test.espresso.matcher.RootMatchers.isDialog
onView(withText("Submit")).inRoot(isDialog()).perform(click())Same applies to popup menus () and toasts.
isPlatformPopup()kotlin
// WRONG
onView(withText("Submit")).perform(click())
// WRONG because: RootMatchers.DEFAULT (line 51 of RootMatchers.java) excludes dialogs.
// The matcher does not see the dialog window. Result: NoMatchingViewException ("No views in
// hierarchy found matching: with text Submit"), even though the dialog is clearly on screen.kotlin
// RIGHT
import androidx.test.espresso.matcher.RootMatchers.isDialog
onView(withText("Submit")).inRoot(isDialog()).perform(click())同样适用于弹出菜单()和 toast。
isPlatformPopup()Pattern: WRONG vs RIGHT — BottomNavigationView
interaction (Espresso 3.7.0 contrib)
BottomNavigationView模式:错误与正确——BottomNavigationView
交互(Espresso 3.7.0 contrib)
BottomNavigationViewkotlin
// WRONG
import androidx.test.espresso.contrib.BottomNavigationViewActions
onView(withId(R.id.bottom_nav)).perform(BottomNavigationViewActions.selectItem(R.id.tab_profile))
// WRONG because: BottomNavigationViewActions does NOT exist in espresso-contrib 3.7.0.
// The class was historically documented but never shipped in 3.7.0's contrib jar (R3 lines 91-93).
// Compile fails with "unresolved reference".kotlin
// RIGHT — click the underlying menu item view directly
import com.google.android.material.bottomnavigation.BottomNavigationView
import org.hamcrest.Matchers.allOf
onView(allOf(
withId(R.id.tab_profile),
isDescendantOfA(isAssignableFrom(BottomNavigationView::class.java)),
)).perform(click())kotlin
// WRONG
import androidx.test.espresso.contrib.BottomNavigationViewActions
onView(withId(R.id.bottom_nav)).perform(BottomNavigationViewActions.selectItem(R.id.tab_profile))
// WRONG because: BottomNavigationViewActions does NOT exist in espresso-contrib 3.7.0.
// The class was historically documented but never shipped in 3.7.0's contrib jar (R3 lines 91-93).
// Compile fails with "unresolved reference".kotlin
// RIGHT — click the underlying menu item view directly
import com.google.android.material.bottomnavigation.BottomNavigationView
import org.hamcrest.Matchers.allOf
onView(allOf(
withId(R.id.tab_profile),
isDescendantOfA(isAssignableFrom(BottomNavigationView::class.java)),
)).perform(click())Pattern: WRONG vs RIGHT — PickerActions.setDate
month convention
PickerActions.setDate模式:错误与正确——PickerActions.setDate
月份约定
PickerActions.setDatekotlin
// WRONG
import androidx.test.espresso.contrib.PickerActions
onView(withClassName(equalTo(DatePicker::class.java.name)))
.perform(PickerActions.setDate(2026, 4, 15)) // intends "May 15, 2026"
// WRONG because: PickerActions.setDate uses 1-12 month convention (it subtracts 1 internally
// before calling DatePicker.updateDate which uses 0-11). Passing 4 sets April, not May.
// Source: R3 line 460, PickerActions.java line 49.kotlin
// RIGHT — May = 5
onView(withClassName(equalTo(DatePicker::class.java.name)))
.perform(PickerActions.setDate(2026, 5, 15))kotlin
// WRONG
import androidx.test.espresso.contrib.PickerActions
onView(withClassName(equalTo(DatePicker::class.java.name)))
.perform(PickerActions.setDate(2026, 4, 15)) // intends "May 15, 2026"
// WRONG because: PickerActions.setDate uses 1-12 month convention (it subtracts 1 internally
// before calling DatePicker.updateDate which uses 0-11). Passing 4 sets April, not May.
// Source: R3 line 460, PickerActions.java line 49.kotlin
// RIGHT — May = 5
onView(withClassName(equalTo(DatePicker::class.java.name)))
.perform(PickerActions.setDate(2026, 5, 15))Pattern: WRONG vs RIGHT — Thread.sleep
to wait for an animation
Thread.sleep模式:错误与正确——使用 Thread.sleep
等待动画
Thread.sleepkotlin
// WRONG
onView(withId(R.id.fab)).perform(click())
Thread.sleep(500) // wait for the FAB exit animation
onView(withId(R.id.fab)).check(doesNotExist())
// WRONG because: Thread.sleep is a smell. Espresso's idle pump already waits for animations
// driven through the main looper; if it doesn't, register an IdlingResource for the offending
// async path. See `docs/CORPUS.md` D.7 — "Thread.sleep is a smell".kotlin
// RIGHT — disable animations OR register an IdlingResource
android.testOptions.animationsDisabled = true // for property animators driven via Choreographer
// And/or, for non-Looper waits:
IdlingPolicies.setMasterPolicyTimeout(45, TimeUnit.SECONDS)
IdlingRegistry.getInstance().register(myAnimationIdler)kotlin
// WRONG
onView(withId(R.id.fab)).perform(click())
Thread.sleep(500) // wait for the FAB exit animation
onView(withId(R.id.fab)).check(doesNotExist())
// WRONG because: Thread.sleep is a smell. Espresso's idle pump already waits for animations
// driven through the main looper; if it doesn't, register an IdlingResource for the offending
// async path. See `docs/CORPUS.md` D.7 — "Thread.sleep is a smell".kotlin
// RIGHT — disable animations OR register an IdlingResource
android.testOptions.animationsDisabled = true // for property animators driven via Choreographer
// And/or, for non-Looper waits:
IdlingPolicies.setMasterPolicyTimeout(45, TimeUnit.SECONDS)
IdlingRegistry.getInstance().register(myAnimationIdler)Pattern: scrolling a RecyclerView
to an off-screen row before clicking it
RecyclerView模式:点击屏幕外的 RecyclerView
行前先滚动到该行
RecyclerViewkotlin
import androidx.test.espresso.contrib.RecyclerViewActions.*
import androidx.test.espresso.matcher.ViewMatchers.hasDescendant
onView(withId(R.id.list))
.perform(scrollTo<RecyclerView.ViewHolder>(hasDescendant(withText("Snorlax"))))
onView(withId(R.id.list))
.perform(actionOnItem<RecyclerView.ViewHolder>(hasDescendant(withText("Snorlax")), click()))scrollToactionOnItemRecyclerView.ViewHolderMatcher<View>kotlin
import androidx.test.espresso.contrib.RecyclerViewActions.*
import androidx.test.espresso.matcher.ViewMatchers.hasDescendant
onView(withId(R.id.list))
.perform(scrollTo<RecyclerView.ViewHolder>(hasDescendant(withText("Snorlax"))))
onView(withId(R.id.list))
.perform(actionOnItem<RecyclerView.ViewHolder>(hasDescendant(withText("Snorlax")), click()))scrollToactionOnItemRecyclerView.ViewHolderMatcher<View>Mandatory rules
强制规则
- MUST add for any matcher targeting an
.inRoot(isDialog())content view,AlertDialogfor popup menus and toasts..inRoot(isPlatformPopup())excludes them.RootMatchers.DEFAULT - MUST prefer /
withId/withTagKeyoverwithResourceName. Text matchers are i18n-fragile and churn with copy edits.withText - MUST NOT rely on to wait for animations or async work. Use
Thread.sleep+IdlingResource, andIdlingPolicies.setMasterPolicyTimeout.testOptions.animationsDisabled = true - MUST NOT import — the class is not in
androidx.test.espresso.contrib.BottomNavigationViewActions. Use theespresso-contrib:3.7.0workaround.isDescendantOfA(isAssignableFrom(BottomNavigationView::class.java)) - MUST pass 1-12 (not 0-11) for the month parameter of . The action subtracts 1 internally before calling
PickerActions.setDate(year, month, day).DatePicker.updateDate - MUST call /
Intents.init()(or useIntents.release()) —IntentsRule/intendedonly work between those calls.intending - MUST put on
:espresso-idling-resource:3.7.0(production), notimplementation. The production code is what increments / decrements the resource.androidTestImplementation - MUST NOT use — it is
IntentsTestRule. Use@Deprecated(3.5+) or manualIntentsRule/init.release - PREFERRED: disable animations globally via ; do not toggle
testOptions.animationsDisabled = trueflags by hand.Settings.Global - PREFERRED: read every message — it includes a hierarchy dump. The view you wanted may be present but in a different
NoMatchingViewException.Root
- 必须为任何针对 内容 View 的 matcher 添加
AlertDialog;对于弹出菜单和 toast,则添加.inRoot(isDialog())。.inRoot(isPlatformPopup())会排除它们。RootMatchers.DEFAULT - 必须优先使用 /
withId/withTagKey,而不是withResourceName。文本 matcher 容易受 i18n 影响,并会因文案修改而频繁变动。withText - 不得依赖 等待动画或异步工作。请使用
Thread.sleep+IdlingResource,并设置IdlingPolicies.setMasterPolicyTimeout。testOptions.animationsDisabled = true - 不得导入 ——该类不在
androidx.test.espresso.contrib.BottomNavigationViewActions中。请使用espresso-contrib:3.7.0变通方案。isDescendantOfA(isAssignableFrom(BottomNavigationView::class.java)) - 必须为 的月份参数传入 1-12(而不是 0-11)。该 action 会在调用
PickerActions.setDate(year, month, day)前在内部减去 1。DatePicker.updateDate - 必须调用 /
Intents.init()(或使用Intents.release())——只有在这两次调用之间,IntentsRule/intended才能正常工作。intending - 必须将 放在
:espresso-idling-resource:3.7.0(生产代码)中,而不是implementation。负责递增和递减资源计数的代码位于生产代码中。androidTestImplementation - 不得使用 ——它已标记为
IntentsTestRule。请使用@Deprecated(3.5+),或手动调用IntentsRule/init。release - **首选:**通过 全局禁用动画;不要手动切换
testOptions.animationsDisabled = true标志。Settings.Global - **首选:**阅读每一条 消息——其中包含层级 dump。目标 View 可能已经存在,只是位于不同的
NoMatchingViewException中。Root
Verification
验证
- returns nothing (or only screenshot-test files where the RenderThread is the wait target).
grep -r "Thread.sleep" src/androidTest/ - returns nothing.
grep -r "BottomNavigationViewActions" src/androidTest/ - returns nothing — use
grep -r "IntentsTestRule" src/androidTest/or manual init/release.IntentsRule - Every matches an
inRoot(isDialog())-class API in production; otherwise the test passes against the wrong root.AlertDialog - runs without
./gradlew :<module>:connectedDebugAndroidTestorNoMatchingViewExceptionfrom the catalog above.PerformException - is set in the module's
testOptions.animationsDisabled = trueblock.android - All registered s call
IdlingResourceinIdlingRegistry.getInstance().unregister(...)(or use a JUnit rule).@After
- 没有返回任何结果(或仅在以 RenderThread 为等待目标的 screenshot-test 文件中存在)。
grep -r "Thread.sleep" src/androidTest/ - 没有返回任何结果。
grep -r "BottomNavigationViewActions" src/androidTest/ - 没有返回任何结果——请使用
grep -r "IntentsTestRule" src/androidTest/或手动 init/release。IntentsRule - 每个 都与生产代码中的
inRoot(isDialog())类 API 匹配;否则测试可能是针对错误的 root 通过的。AlertDialog - 运行 时,没有出现上述目录中列出的
./gradlew :<module>:connectedDebugAndroidTest或NoMatchingViewException。PerformException - 模块的 block 中已设置
android。testOptions.animationsDisabled = true - 所有已注册的 都在
IdlingResource中调用@After(或使用 JUnit rule)。IdlingRegistry.getInstance().unregister(...)
References
参考资料
- Android Developers — Espresso overview: https://developer.android.com/training/testing/espresso
- Android Developers — Espresso cheat sheet (matchers, actions, assertions): https://developer.android.com/training/testing/espresso/cheat-sheet
- Android Developers — IdlingResource guide: https://developer.android.com/training/testing/espresso/idling-resource
- AndroidX Test (Espresso) release notes: https://developer.android.com/jetpack/androidx/releases/test
- (lines 79-1000+) — full matcher catalog. Identity (
androidx/test/espresso/matcher/ViewMatchers.java,withId,withTagKey); text (withResourceName,withText,withSubstring); state (withHint,isDisplayed,isEnabled,isChecked); hierarchy (withEffectiveVisibility,withParent,hasDescendant,withChild,isRoot).isDescendantOfA - line 51 —
androidx/test/espresso/matcher/RootMatchers.java. The trap.DEFAULT = allOf(hasWindowLayoutParams(), allOf(anyOf(allOf(isDialog(), withDecorView(hasWindowFocus())), isSubwindowOfCurrentActivity()), isFocusable())) - —
androidx/test/espresso/action/ViewActions.java,click,longClick,doubleClick,typeText,replaceText,clearText,pressKey,swipeUp/Down/Left/Right,scrollTo,pressImeActionButton.closeSoftKeyboard - lines 51-118 —
androidx/test/espresso/assertion/ViewAssertions.java,matches,doesNotExist.selectedDescendantsMatch - lines 200-249 —
androidx/test/espresso/contrib/RecyclerViewActions.java,scrollToPosition,scrollTo,actionOnItemAtPosition. Constraint:actionOnItem.isAssignableFrom(RecyclerView) AND isDisplayed - lines 36-100 —
androidx/test/espresso/contrib/PickerActions.javawith monthOfYear 1-12 (line 49 KDoc).setDate(year, monthOfYear, dayOfMonth).setTime(hours, minutes) - lines 96-112 —
androidx/test/espresso/IdlingPolicies.java,setMasterPolicyTimeout,setIdlingResourceTimeout.setMasterPolicyTimeoutWhenDebuggerAttached - —
androidx/test/espresso/intent/Intents.java,init,release,intended.intendingis the modern JUnit4 wrapper.androidx.test.espresso.intent.rule.IntentsRule - — full Espresso 3.7.0 deep-dive. Lines 91-93 (BottomNavigationViewActions absent), 311 (RootMatchers.DEFAULT), 456-460 (PickerActions month convention), 811-820 (idle-then-act).
tasks/research/R3-espresso.md - Section H.5 — Espresso essentials and
docs/CORPUS.mdexclusions.RootMatchers.DEFAULT
- Android Developers——Espresso 概览:https://developer.android.com/training/testing/espresso
- Android Developers——Espresso 速查表(matcher、action、assertion):https://developer.android.com/training/testing/espresso/cheat-sheet
- Android Developers——指南:https://developer.android.com/training/testing/espresso/idling-resource
IdlingResource - AndroidX Test(Espresso)发行说明:https://developer.android.com/jetpack/androidx/releases/test
- (第 79-1000+ 行)——完整 matcher 目录。标识匹配(
androidx/test/espresso/matcher/ViewMatchers.java、withId、withTagKey);文本匹配(withResourceName、withText、withSubstring);状态匹配(withHint、isDisplayed、isEnabled、isChecked);层级匹配(withEffectiveVisibility、withParent、hasDescendant、withChild、isRoot)。isDescendantOfA - 第 51 行——
androidx/test/espresso/matcher/RootMatchers.java。陷阱所在。DEFAULT = allOf(hasWindowLayoutParams(), allOf(anyOf(allOf(isDialog(), withDecorView(hasWindowFocus())), isSubwindowOfCurrentActivity()), isFocusable())) - ——
androidx/test/espresso/action/ViewActions.java、click、longClick、doubleClick、typeText、replaceText、clearText、pressKey、swipeUp/Down/Left/Right、scrollTo、pressImeActionButton。closeSoftKeyboard - 第 51-118 行——
androidx/test/espresso/assertion/ViewAssertions.java、matches、doesNotExist。selectedDescendantsMatch - 第 200-249 行——
androidx/test/espresso/contrib/RecyclerViewActions.java、scrollToPosition、scrollTo、actionOnItemAtPosition。Constraint:actionOnItem。isAssignableFrom(RecyclerView) AND isDisplayed - 第 36-100 行——
androidx/test/espresso/contrib/PickerActions.java,其中 monthOfYear 为 1-12(第 49 行 KDoc)。setDate(year, monthOfYear, dayOfMonth)。setTime(hours, minutes) - 第 96-112 行——
androidx/test/espresso/IdlingPolicies.java、setMasterPolicyTimeout、setIdlingResourceTimeout。setMasterPolicyTimeoutWhenDebuggerAttached - ——
androidx/test/espresso/intent/Intents.java、init、release、intended。intending是现代 JUnit4 wrapper。androidx.test.espresso.intent.rule.IntentsRule - ——Espresso 3.7.0 深入分析。第 91-93 行(缺少
tasks/research/R3-espresso.md)、第 311 行(BottomNavigationViewActions)、第 456-460 行(RootMatchers.DEFAULT月份约定)、第 811-820 行(先空闲、再操作)。PickerActions - H.5 节——Espresso 核心内容和
docs/CORPUS.md排除规则。RootMatchers.DEFAULT