我正在尝试测试 Text
在我的组件上我可以用不同的颜色打印它,所以在我的测试中我正在验证它是否获得了预期的颜色。我正在寻找一种返回颜色的方法,但我没有找到任何方法。
从现在开始,我断言文本是正确的并且可见性是正确的,但是当试图找到获得颜色的方法时,我变得太深了,我正在寻找一个更简单的解决方案。
composeTestRule.onNode(hasTestTag("testTagForButton"), true)
.assertExists()
.assertTextEquals("Testing")
我已经检查过我是否可以执行 .fetchSemanticsNode().layoutInfo.getModifierInfo()
之类的操作进入Modifier
也许从那里我可以得到颜色,但它可能太多了。我也发现了这个 .captureToImage()
也许我可以在上面涂上颜色,但是由于我必须放置像素,所以我认为这不是办法。有什么简单的方法可以得到吗?
最佳答案
我绝不是 compose 专家,但只看 compose 源代码,你可以利用他们的 GetTextLayoutResult可访问性语义 Action 。这将包含用于渲染 Text
的所有属性。在 Canvas 上。
为了方便起见,我提出了一些快速而肮脏的扩展功能:
fun SemanticsNodeInteraction.assertTextColor(
color: Color
): SemanticsNodeInteraction = assert(isOfColor(color))
private fun isOfColor(color: Color): SemanticsMatcher = SemanticsMatcher(
"${SemanticsProperties.Text.name} is of color '$color'"
) {
val textLayoutResults = mutableListOf<TextLayoutResult>()
it.config.getOrNull(SemanticsActions.GetTextLayoutResult)
?.action
?.invoke(textLayoutResults)
return@SemanticsMatcher if (textLayoutResults.isEmpty()) {
false
} else {
textLayoutResults.first().layoutInput.style.color == color
}
}
然后可以像这样使用它:composeTestRule.onNode(hasTestTag("testTagForButton"), true)
.assertExists()
.assertTextEquals("Testing")
.assertTextColor(Color.Black)
关于android - 撰写 UI 测试 - 如何断言文本颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70988755/