Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if the given function was called in compose test

Let's say I have a composable like this which I want to test

@Composable
fun HelloContent(sayHello: () -> Unit) {
 Button(text = "Hello World", onClick = sayHello)
}

How to test if sayHello was called from compose test. I tried using mockk but that didn't seem to work

@Test
fun check_if_sayHello_was_called() {
  composeTestRule.setContent {
     HelloContent(sayHello = mockk())
}

composeTestRule.onNodeWithText("Hello World").performClick()
// How to test if sayHello was called
}
like image 652
Android Newcomer Avatar asked Sep 01 '26 08:09

Android Newcomer


1 Answers

@Test
fun check_if_sayHello_was_called() {
    var wasCalled = false
    composeTestRule.setContent {
        HelloContent(sayHello = { wasCalled = true })
    }
    composeTestRule.onNodeWithText("Hello World").assertHasClickAction()
    composeTestRule.onNodeWithText("Hello World").performClick()
    assert(wasCalled)
}

You can use the sayHello: () -> Unit lambda to test a boolean.

like image 176
Thiago Souza Avatar answered Sep 03 '26 21:09

Thiago Souza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!