【问题标题】:assert button color is MaterialTheme.colors.primary in composable断言按钮颜色是可组合的 MaterialTheme.colors.primary
【发布时间】:2023-01-17 19:06:39
【问题描述】:

我有一个简单的按钮。它的颜色集是根据条件设置的,我想测试从 MaterialTheme 应用了正确的颜色,但测试失败说 @Compos

@Composable
fun Btn(shopState: Int) {
    //set color based on the state now, default being primary
    var color = MaterialTheme.colors.primary
     if (shopState == 2) {...}
     else if (shopState == 3) {...}
    Button(onClick = {
        /*
         call calculation method passing the current value of shopState
        */
    }) {
        Text(text = "Calculate", color = color)
    }
}

现在测试文件(从 SO 复制):

fun SemanticsNodeInteraction.assertButtonColor(expectedColor: Color) {
    val capturedName = captureToImage().colorSpace.name
    assertEquals(expectedColor.colorSpace.name, capturedName)
}

但是当我这样做时:

composeTestRule.onNodeWithText("Calculate").assertButtonColor(MaterialTheme.colors.primary)

它不会在 MaterialTheme 的颜色属性下以红线运行:@Composable 调用只能发生在@Composables 中。

如何断言当前应用了 MaterialTheme.colors.primary?

【问题讨论】:

    标签: android android-jetpack-compose android-testing android-jetpack-compose-testing


    【解决方案1】:

    你可以使用类似的东西:

        var onPrimary = Color.Transparent
        var content = Color.Transparent
        rule.setMaterialContent {
            onPrimary = MaterialTheme.colors.onPrimary
            Button(onClick = {}) {
                content = LocalContentColor.current
            }
        }
    
        assertThat(content).isEqualTo(onPrimary)
    

    【讨论】:

    • setMaterialContent 从何而来?
    猜你喜欢
    • 2017-06-10
    • 2016-12-25
    • 1970-01-01
    • 2015-12-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    相关资源
    最近更新 更多