assert button color is MaterialTheme.colors.primary in composable

216 Views Asked by At

I have a simple button. It's color set is set based on condition and I want to test correct color is applied from MaterialTheme but test fails saying @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)
    }
}

Test file now (copied from SO):

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

but when I do:

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

it doesn't run with red line under colors property of MaterialTheme: @Composable invocations can only happen from @Composables.

How do I assert MaterialTheme.colors.primary is currently applied?

1

There are 1 best solutions below

2
On

You can use something like:

import com.google.common.truth.Truth.assertThat

@Test
fun bottonColorTest() {
    var onPrimary = Color.Transparent
    var content = Color.Transparent
    rule.setContent {
        onPrimary = MaterialTheme.colors.onPrimary
        Button(onClick = {}) {
            content = LocalContentColor.current
        }
    }

    assertThat(content).isEqualTo(onPrimary)
}

To import the com.google.common.truth.Truth.assertThat add in your dependency:

androidTestImplementation "com.google.truth:truth:1.1.3"