5

我正在尝试Text在我的组件上测试我可以用不同的颜色打印它,所以在我的测试中我正在验证它是否获得了预期的颜色。我正在寻找一种返回颜色的方法,但我没有找到任何方法。

从现在开始,我断言文本是正确的并且可见性是正确的,但是当试图找到获得颜色的方法时,我变得太深了,我正在寻找一个更简单的解决方案。

composeTestRule.onNode(hasTestTag("testTagForButton"), true)
            .assertExists()
            .assertTextEquals("Testing")

我已经检查过我可以做一些类似.fetchSemanticsNode().layoutInfo.getModifierInfo()的事情Modifier,也许从那里我可以得到颜色,但它可能太多了。另外我发现这个.captureToImage()也许我可以在上面涂上颜色,但是由于我必须放置像素,所以我认为这不是办法。

有什么简单的方法可以得到吗?

4

1 回答 1

4

我绝不是撰写专家,但只要查看撰写源代码,您就可以利用他们的GetTextLayoutResult可访问性语义操作。这将包含用于Text在画布上呈现的所有属性。

为了方便起见,我提出了一些快速而肮脏的扩展功能:

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)
于 2022-02-11T09:02:26.337 回答