arn*_*ans 4

官方 Compose 测试文档中有一个示例,介绍如何使用 来测试是否发生重组,composeTestRule.setContent并在其中使用测试中可见的变量跟踪状态。

然后,您更改测试的状态并断言跟踪变量等于预期状态。

@Test
fun counterTest() {
    val myCounter = mutableStateOf(0) // State that can cause recompositions
    var lastSeenValue = 0 // Used to track recompositions
    composeTestRule.setContent {
        Text(myCounter.value.toString())
        lastSeenValue = myCounter.value
    }
    myCounter.value = 1 // The state changes, but there is no recomposition

    // Fails because nothing triggered a recomposition
    assertTrue(lastSeenValue == 1)

    // Passes because the assertion triggers recomposition
    composeTestRule.onNodeWithText("1").assertExists()
}
Run Code Online (Sandbox Code Playgroud)

此示例用于显示 Compose-Testing 中的边缘情况,即当您在测试中不使用 UI 同步方法时(例如onNodeWithText().assertExists()),但我认为它也可用于您的问题。