composing-semantics-matchers
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseComposing Semantics Matchers — One Matcher, One Error
组合 SemanticsMatcher——一个匹配器,一个错误
A is a description string plus a predicate (). Compose ships with a rich filter library and three combinators (, , ) that produce a single matcher whose error message lists every clause. This skill picks the right factory, composes precise predicates, and replaces brittle assertion chains.
SemanticsMatcher(SemanticsNode) -> BooleanSemanticsMatcher.kt:26andornotSemanticsMatcher(SemanticsNode) -> BooleanSemanticsMatcher.kt:26andornotWhen to use this skill
何时使用此 skill
- The developer wants to find "an enabled Button with text Submit" or any node matching multiple constraints.
- The developer asks how to combine and
hasText, or how to negate a matcher withhasClickAction.not - The developer needs to filter by a custom (e.g. a domain-specific role) using
SemanticsPropertyKey/expectValue.keyIsDefined - The developer asks about hierarchical matchers like ,
hasParent,hasAnyAncestor,hasAnyChild,hasAnySibling.hasAnyDescendant - A test chains multiple calls and the developer wants a single, declarative predicate.
assertIs*
- 开发者希望查找“文本为 Submit 的已启用 Button”,或任何满足多个约束条件的节点。
- 开发者询问如何组合 和
hasText,或如何使用hasClickAction对匹配器取反。not - 开发者需要使用 /
expectValue按自定义keyIsDefined(例如领域特定角色)进行筛选。SemanticsPropertyKey - 开发者询问 、
hasParent、hasAnyAncestor、hasAnyChild、hasAnySibling等层级匹配器。hasAnyDescendant - 测试中链式调用了多个 ,而开发者希望改用单个声明式谓词。
assertIs*
When NOT to use this skill
何时不应使用此 skill
- The query is "find by tag/text/content description only" — use .
../finding-nodes-by-tag-text-content/SKILL.md - The right node exists but only as a relative — use .
../traversing-the-semantics-tree/SKILL.md - The matcher is fine; only the assertions need rework — see .
../../assertions/asserting-node-state-and-text/SKILL.md
- 查询仅按“标签/文本/内容描述”查找——请使用 。
../finding-nodes-by-tag-text-content/SKILL.md - 目标节点存在,但只能通过相对关系找到——请使用 。
../traversing-the-semantics-tree/SKILL.md - 匹配器本身没有问题,只需要重构断言——请参阅 。
../../assertions/asserting-node-state-and-text/SKILL.md
Prerequisites
前置条件
- on the test classpath. See
androidx.compose.ui:ui-testif unresolved.../../setup/configuring-test-dependencies/SKILL.md - Comfort with in production code. Custom keys must be set via
Modifier.semantics { … }to be matchable from tests.Modifier.semantics { customKey = value }
- 测试类路径中包含 。如果无法解析,请参阅
androidx.compose.ui:ui-test。../../setup/configuring-test-dependencies/SKILL.md - 熟悉生产代码中的 。自定义键必须通过
Modifier.semantics { … }设置,才能在测试中进行匹配。Modifier.semantics { customKey = value }
Workflow
工作流
-
1. Build matchers from the prebuilt filter library. Every prebuilt matcher lives in. Group by signal:
commonMain/.../Filters.ktSignal Matchers File:line Enabled / disabled ,isEnabled()isNotEnabled()Filters.kt:38-47Toggle (Switch, Checkbox) ,isToggleable(),isOn()isOff()Filters.kt:54-70Selection (Tab, RadioButton) ,isSelectable(),isSelected()isNotSelected()Filters.kt:77-93Focus ,isFocusable(),isNotFocusable(),isFocused()isNotFocused()Filters.kt:100-122Click action ,hasClickAction()hasNoClickAction()Filters.kt:129-136Scroll action ,hasScrollAction(),hasNoScrollAction(),hasScrollToIndexAction(),hasScrollToKeyAction()hasScrollToNodeAction()Filters.kt:143-425Text actions (TextField) ,hasSetTextAction(),hasInsertTextAtCursorAction(),hasPerformImeAction()hasImeAction(ImeAction)Filters.kt:365-392Focus action hasRequestFocusAction()Filters.kt:399Content description ,hasContentDescription(value, substring, ignoreCase)hasContentDescriptionExactly(vararg)Filters.kt:165-212Text ,hasText(text, substring, ignoreCase)hasTextExactly(vararg, includeEditableText=true)Filters.kt:229-293A11y / state metadata ,hasStateDescription,hasProgressBarRangeInfo,isHeading,isDialog,isPopup,isHiddenFromAccessibility,isEditableisRootFilters.kt:301-439Test tag hasTestTag(testTag)Filters.kt:326-327Hierarchical ,hasParent(matcher),hasAnyChild(matcher),hasAnySibling(matcher),hasAnyAncestor(matcher)hasAnyDescendant(matcher)Filters.kt:446-530searcheshasText,SemanticsProperties.Text, ANDSemanticsProperties.EditableTextsimultaneously (SemanticsProperties.InputText).Filters.kt:229-258matches against the merged list of descriptions (hasContentDescription).Filters.kt:165-188 -
2. Compose with/
and/or. Combinators come fromnot. Each produces a new matcher whoseSemanticsMatcher.kt:60-74readsdescription/(left) && (right)/(left) || (right). The framework prints this description verbatim on assertion failure, so the failure message shows exactly which clause(s) failed.NOT (inner) -
3. Usefor custom keys. When the production code declares a custom
SemanticsMatcher.expectValueand writes it viaSemanticsPropertyKey<T>, match it withModifier.semantics { customKey = value }(SemanticsMatcher.expectValue(customKey, expectedValue)). For "this key is set at all", useSemanticsMatcher.kt:33-37(SemanticsMatcher.keyIsDefined(customKey)); for "this key is NOT set", useSemanticsMatcher.kt:40-42(keyNotDefined). Built-in matchers likeSemanticsMatcher.kt:45-47are themselves thin wrappers overisOn()(expectValue(SemanticsProperties.ToggleableState, On)).Filters.kt:61-62 -
4. Pass the composed matcher to/
onNode.onAllNodesandonNode(matcher, useUnmergedTree=false)are the canonical entry points (onAllNodes(matcher, useUnmergedTree=false)). BothSemanticsNodeInteractionsProvider.ktand friends are convenience wrappers — drop them when the predicate gets richer.onNodeWithTag -
5. For hierarchical assertions, prefer/
hasAnyAncestorover multiple traversal steps. Example: "find the Text inside the dialog" →hasAnyDescendant. Cleaner thanonNode(hasText("Discard?") and hasAnyAncestor(isDialog())).onAllNodes(isDialog()).onFirst().onChildren().filter(hasText(...)).onFirst()
-
1. 从预置筛选器库构建匹配器。 每个预置匹配器都位于中。可按信号对它们进行分组:
commonMain/.../Filters.kt信号 匹配器 文件:行 启用/禁用 、isEnabled()isNotEnabled()Filters.kt:38-47切换(Switch、Checkbox) 、isToggleable()、isOn()isOff()Filters.kt:54-70选择(Tab、RadioButton) 、isSelectable()、isSelected()isNotSelected()Filters.kt:77-93焦点 、isFocusable()、isNotFocusable()、isFocused()isNotFocused()Filters.kt:100-122点击操作 、hasClickAction()hasNoClickAction()Filters.kt:129-136滚动操作 、hasScrollAction()、hasNoScrollAction()、hasScrollToIndexAction()、hasScrollToKeyAction()hasScrollToNodeAction()Filters.kt:143-425文本操作(TextField) 、hasSetTextAction()、hasInsertTextAtCursorAction()、hasPerformImeAction()hasImeAction(ImeAction)Filters.kt:365-392焦点操作 hasRequestFocusAction()Filters.kt:399内容描述 、hasContentDescription(value, substring, ignoreCase)hasContentDescriptionExactly(vararg)Filters.kt:165-212文本 、hasText(text, substring, ignoreCase)hasTextExactly(vararg, includeEditableText=true)Filters.kt:229-293无障碍/状态元数据 、hasStateDescription、hasProgressBarRangeInfo、isHeading、isDialog、isPopup、isHiddenFromAccessibility、isEditableisRootFilters.kt:301-439测试标签 hasTestTag(testTag)Filters.kt:326-327层级关系 、hasParent(matcher)、hasAnyChild(matcher)、hasAnySibling(matcher)、hasAnyAncestor(matcher)hasAnyDescendant(matcher)Filters.kt:446-530会同时搜索hasText、SemanticsProperties.Text和SemanticsProperties.EditableText(SemanticsProperties.InputText)。Filters.kt:229-258会与合并后的描述列表进行匹配(hasContentDescription)。Filters.kt:165-188 -
2. 使用/
and/or进行组合。 组合器来自not。每个组合器都会生成一个新的匹配器,其SemanticsMatcher.kt:60-74显示为description/(left) && (right)/(left) || (right)。框架在断言失败时原样打印此描述,因此失败消息会准确显示哪些子句失败。NOT (inner) -
3. 使用处理自定义键。 当生产代码声明自定义
SemanticsMatcher.expectValue并通过SemanticsPropertyKey<T>写入时,使用Modifier.semantics { customKey = value }进行匹配(SemanticsMatcher.expectValue(customKey, expectedValue))。如果要判断“这个键已设置”,使用SemanticsMatcher.kt:33-37(SemanticsMatcher.keyIsDefined(customKey));如果要判断“这个键未设置”,使用SemanticsMatcher.kt:40-42(keyNotDefined)。SemanticsMatcher.kt:45-47等内置匹配器本质上是对isOn()的轻量封装(expectValue(SemanticsProperties.ToggleableState, On))。Filters.kt:61-62 -
4. 将组合后的匹配器传给/
onNode。onAllNodes和onNode(matcher, useUnmergedTree=false)是标准入口(onAllNodes(matcher, useUnmergedTree=false))。SemanticsNodeInteractionsProvider.kt等函数都是便捷包装器——当谓词变得更丰富时,应改用这些基础入口。onNodeWithTag -
5. 对于层级断言,如果关系是“位于上方或下方的任意位置”,优先使用/
hasAnyAncestor,而不是执行多个遍历步骤。 示例:“查找对话框内的 Text”→hasAnyDescendant。这比onNode(hasText("Discard?") and hasAnyAncestor(isDialog()))更简洁。onAllNodes(isDialog()).onFirst().onChildren().filter(hasText(...)).onFirst()
Patterns
模式
Pattern: replace assertion chains with a single matcher
模式:用单个匹配器替换断言链
kotlin
// WRONG
@Test
fun submit_isEnabledClickable() {
rule.setContent { CheckoutScreen() }
rule.onNodeWithText("Submit")
.assertHasClickAction()
.assertIsEnabled()
}
// WRONG because: each assertion is a separate fetch + error path. Failure prints "no click
// action" without telling the developer the matched node is the *enabled-but-wrong* button on
// a different screen.kotlin
// RIGHT
@Test
fun submit_isEnabledClickable() {
rule.setContent { CheckoutScreen() }
rule.onNode(hasText("Submit") and hasClickAction() and isEnabled())
.assertExists()
}The composed matcher's description prints on failure, naming every unsatisfied clause.
(Text + InputText + EditableText contains 'Submit' (ignoreCase: false)) && (OnClick is defined) && (is enabled)kotlin
// WRONG
@Test
fun submit_isEnabledClickable() {
rule.setContent { CheckoutScreen() }
rule.onNodeWithText("Submit")
.assertHasClickAction()
.assertIsEnabled()
}
// WRONG because: each assertion is a separate fetch + error path. Failure prints "no click
// action" without telling the developer the matched node is the *enabled-but-wrong* button on
// a different screen.kotlin
// RIGHT
@Test
fun submit_isEnabledClickable() {
rule.setContent { CheckoutScreen() }
rule.onNode(hasText("Submit") and hasClickAction() and isEnabled())
.assertExists()
}组合后的匹配器描述会输出 ,失败时会列出每个未满足的子句。
(Text + InputText + EditableText contains 'Submit' (ignoreCase: false)) && (OnClick is defined) && (is enabled)Pattern: hierarchical match — "the Text inside the dialog"
模式:层级匹配——“对话框内的 Text”
kotlin
// WRONG
rule.onAllNodes(isDialog())
.onFirst()
.onChildren()
.filterToOne(hasText("Discard?"))
.assertIsDisplayed()
// WRONG because: it implicitly assumes the Text is a direct child of the dialog root.
// AlertDialog wraps its body in Column/Surface, so the Text is a descendant, not a child.kotlin
// RIGHT
rule.onNode(hasText("Discard?") and hasAnyAncestor(isDialog()))
.assertIsDisplayed()kotlin
// WRONG
rule.onAllNodes(isDialog())
.onFirst()
.onChildren()
.filterToOne(hasText("Discard?"))
.assertIsDisplayed()
// WRONG because: it implicitly assumes the Text is a direct child of the dialog root.
// AlertDialog wraps its body in Column/Surface, so the Text is a descendant, not a child.kotlin
// RIGHT
rule.onNode(hasText("Discard?") and hasAnyAncestor(isDialog()))
.assertIsDisplayed()Pattern: negation and "exactly one"
模式:取反与“恰好一个”
kotlin
// "An enabled, non-toggleable Button (so: not a Switch or Checkbox) with text Submit"
rule.onNode(hasText("Submit") and isEnabled() and !isToggleable())
.assertHasClickAction()!matcheroperator fun not()SemanticsMatcher.kt:72-74kotlin
// "An enabled, non-toggleable Button (so: not a Switch or Checkbox) with text Submit"
rule.onNode(hasText("Submit") and isEnabled() and !isToggleable())
.assertHasClickAction()!matcheroperator fun not()SemanticsMatcher.kt:72-74Pattern: custom semantics key
模式:自定义语义键
kotlin
// production:
val PriorityKey = SemanticsPropertyKey<Int>("Priority")
var SemanticsPropertyReceiver.priority by PriorityKey
@Composable
fun TaskRow(task: Task) {
Row(modifier = Modifier
.testTag(TaskRowTag)
.semantics { priority = task.priority }
) { /* … */ }
}
// test:
rule.onNode(hasTestTag(TaskRowTag) and SemanticsMatcher.expectValue(PriorityKey, 1))
.assertIsDisplayed()
// "this row has a priority assigned at all":
rule.onNode(hasTestTag(TaskRowTag) and SemanticsMatcher.keyIsDefined(PriorityKey))
.assertIsDisplayed()kotlin
// production:
val PriorityKey = SemanticsPropertyKey<Int>("Priority")
var SemanticsPropertyReceiver.priority by PriorityKey
@Composable
fun TaskRow(task: Task) {
Row(modifier = Modifier
.testTag(TaskRowTag)
.semantics { priority = task.priority }
) { /* … */ }
}
// test:
rule.onNode(hasTestTag(TaskRowTag) and SemanticsMatcher.expectValue(PriorityKey, 1))
.assertIsDisplayed()
// "this row has a priority assigned at all":
rule.onNode(hasTestTag(TaskRowTag) and SemanticsMatcher.keyIsDefined(PriorityKey))
.assertIsDisplayed()Pattern: dropdown / IME-action / scroll-to-key — narrow a TextField query
模式:下拉列表 / IME 操作 / 滚动到键——收窄 TextField 查询
kotlin
// "the editable TextField that handles Done as IME action"
rule.onNode(hasSetTextAction() and hasImeAction(ImeAction.Done))
.performTextInput("hello")
// "any LazyColumn child reachable by key — i.e. has IndexForKey on top of ScrollToIndex"
rule.onNode(hasScrollToKeyAction()).performScrollToKey(itemKey)hasScrollToKeyActionhasKey(ScrollToIndex) and hasKey(IndexForKey)Filters.kt:415-416hasScrollToNodeActionFilters.kt:419-425kotlin
// "the editable TextField that handles Done as IME action"
rule.onNode(hasSetTextAction() and hasImeAction(ImeAction.Done))
.performTextInput("hello")
// "any LazyColumn child reachable by key — i.e. has IndexForKey on top of ScrollToIndex"
rule.onNode(hasScrollToKeyAction()).performScrollToKey(itemKey)hasScrollToKeyActionhasKey(ScrollToIndex) and hasKey(IndexForKey)Filters.kt:415-416hasScrollToNodeActionFilters.kt:419-425Pattern: matcher description appears in error messages
模式:匹配器描述会出现在错误消息中
kotlin
val matcher = hasText("Submit") and hasClickAction() and isEnabled()
println(matcher.description)
// (Text + InputText + EditableText contains 'Submit' (ignoreCase: false)) &&
// (OnClick is defined) && (is enabled)The description is human-readable and used by () when the matcher does not hold. Clauses MUST be readable in isolation — that is why named matchers are preferred over inline lambdas.
assert(matcher)Assertions.kt:254-267kotlin
val matcher = hasText("Submit") and hasClickAction() and isEnabled()
println(matcher.description)
// (Text + InputText + EditableText contains 'Submit' (ignoreCase: false)) &&
// (OnClick is defined) && (is enabled)该描述是人类可读的,并会在匹配器不成立时由 ()使用。每个子句都必须能够被单独阅读——因此应优先使用命名匹配器,而不是内联 lambda。
assert(matcher)Assertions.kt:254-267Mandatory rules
强制规则
- MUST use /
infix and/infix orto compose matchers; MUST NOT chainoperator notcalls when a single composed matcher captures the same intent.assertIs* - MUST wrap custom semantics keys with or
SemanticsMatcher.expectValue(...); MUST NOT accessSemanticsMatcher.keyIsDefined(...)from inside an ad-hoc lambda. The factory methods produce readable error descriptions.node.config[CustomKey] - MUST prefer /
hasAnyAncestor(isDialog())over multi-step traversal when the relationship is "somewhere above/below". Cross-reference:hasAnyDescendant(...).../traversing-the-semantics-tree/SKILL.md - MUST keep the flag at its default
useUnmergedTreeunless the matcher targets an inner element collapsed by merge. Skydoves hot take #2.false - MUST NOT redefine an existing prebuilt matcher (e.g. writing a custom ) — use
SemanticsMatcher("is enabled") { … }. Custom matchers are reserved for keys that don't have a prebuilt filter.isEnabled() - PREFERRED: prefer tag-anchored matchers — — over text-anchored. Skydoves hot take #1.
hasTestTag(SubmitTag) and isEnabled()
- 必须使用 /
infix and/infix or组合匹配器;当单个组合匹配器可以表达相同意图时,不得链式调用operator not。assertIs* - 必须使用 或
SemanticsMatcher.expectValue(...)包装自定义语义键;不得在临时 lambda 中直接访问SemanticsMatcher.keyIsDefined(...)。工厂方法能够生成可读的错误描述。node.config[CustomKey] - 当关系是“位于上方或下方的任意位置”时,必须优先使用 /
hasAnyAncestor(isDialog()),而不是执行多步遍历。交叉参考:hasAnyDescendant(...)。../traversing-the-semantics-tree/SKILL.md - 除非匹配器针对的是被 merge 折叠的内部元素,否则必须保持 标志的默认值
useUnmergedTree。Skydoves 热门观点 #2。false - 不得重新定义已有的预置匹配器(例如编写自定义 )——请使用
SemanticsMatcher("is enabled") { … }。自定义匹配器仅用于没有预置筛选器的键。isEnabled() - **首选:**优先使用以标签为锚点的匹配器,例如 ,而不是以文本为锚点的匹配器。Skydoves 热门观点 #1。
hasTestTag(SubmitTag) and isEnabled()
Verification
验证
- Every multi-condition query uses one rather than chained finders + assertions.
onNode(matcher) - Custom key checks use /
SemanticsMatcher.expectValue—keyIsDefineddoes not appear in matcher predicates.node.config[...] - or
./gradlew :app:connectedDebugAndroidTestpasses.:app:testDebugUnitTest - Failure messages from intentionally-broken matchers print the composed so the failing clause is identifiable.
description - No matcher is silently shadowed by a re-declared local lambda with the same name.
- 每个多条件查询都使用单个 ,而不是链式查找器加断言。
onNode(matcher) - 自定义键检查使用 /
SemanticsMatcher.expectValue,匹配器谓词中未出现keyIsDefined。node.config[...] - 或
./gradlew :app:connectedDebugAndroidTest通过。:app:testDebugUnitTest - 故意破坏的匹配器所产生的失败消息会打印组合后的 ,从而能够识别失败子句。
description - 没有匹配器被重新声明的同名局部 lambda 静默遮蔽。
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
- Semantics in Compose: https://developer.android.com/develop/ui/compose/accessibility/semantics
- —
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsMatcher.kt,class SemanticsMatcher/expectValue/keyIsDefined,keyNotDefined,infix and,infix or.operator not - — every prebuilt matcher (state, action, text, hierarchical).
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Filters.kt - —
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Assertions.ktand how the matcher description surfaces in errors.fun assert(matcher, messagePrefixOnError) - —
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsNodeInteractionsProvider.kt/onNode(matcher, useUnmergedTree).onAllNodes(matcher, useUnmergedTree)
- Compose 测试概览:https://developer.android.com/develop/ui/compose/testing
- Compose 测试速查表:https://developer.android.com/develop/ui/compose/testing-cheatsheet
- Compose 中的 Semantics:https://developer.android.com/develop/ui/compose/accessibility/semantics
- ——
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsMatcher.kt、class SemanticsMatcher/expectValue/keyIsDefined、keyNotDefined、infix and、infix or。operator not - ——所有预置匹配器(状态、操作、文本、层级关系)。
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Filters.kt - ——
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Assertions.kt,以及匹配器描述如何显示在错误中。fun assert(matcher, messagePrefixOnError) - ——
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsNodeInteractionsProvider.kt/onNode(matcher, useUnmergedTree)。onAllNodes(matcher, useUnmergedTree)