compose 无法测试 Dialog

compose can not test Dialog

我在撰写中有对话框:

@Composable
fun testgtt() {
    val saveDialogState = remember { mutableStateOf(false) }
    Button(onClick = { saveDialogState.value = true }, modifier = Modifier.testTag(PLACE_TAG)) {
        Text(text = "helllow")
    }

    Dialog(onDismissRequest = { saveDialogState.value = false }) {
        Text(text = "helllow",modifier = Modifier.testTag(BUTTON_TAG))
    }
}

并想测试它:

    @Test
    fun das(){
        composeTestRule.setContent {
            TerTheme {
                testgtt()
            }
        }
        composeTestRule.onRoot(useUnmergedTree = true).printToLog("currentLabelExists")
        composeTestRule.onNodeWithTag(PLACE_TAG).performClick()
        composeTestRule.onNodeWithTag(BUTTON_TAG).assertIsDisplayed()
    }

但是我得到这个错误:

java.lang.AssertionError: Failed: assertExists.
Reason: Expected exactly '1' node but found '2' nodes that satisfy: (isRoot)
Nodes found:
1) Node #1 at (l=0.0, t=0.0, r=206.0, b=126.0)px
Has 1 child
2) Node #78 at (l=0.0, t=0.0, r=116.0, b=49.0)px
Has 1 child

尽管我看到了对话框本身。

使用导航组件:

@Composable
fun de(){
    val navController = rememberNavController()
    Scaffold { innerPadding ->
        NavHost(navController, "home", Modifier.padding(innerPadding)) {
            composable("home") {
                // This content fills the area provided to the NavHost
                val saveDialogState = remember { mutableStateOf(true) }
                Button(onClick = {
                                 navController.navigate("detail_dialog")
                }, modifier = Modifier.testTag(PLACE_TAG)) {
                    Text(text = "helllow")
                }
            }
            dialog("detail_dialog") {
                // This content will be automatically added to a Dialog() composable
                // and appear above the HomeScreen or other composable destinations
                
        Dialog(onDismissRequest = {navController.navigate("home")}) {
        Card(
            shape = RoundedCornerShape(10.dp),
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight()
//                    .padding(horizontal = 16.dp)
                .padding(vertical = 8.dp),
            elevation = 8.dp
        ){
        Text(text = "helllow", modifier = Modifier.testTag(BUTTON_TAG))
        }
    }
            }
        }
    }
}

此错误的原因是行:composeTestRule.onRoot(useUnmergedTree = true).printToLog("currentLabelExists")

onRoot 需要一个节点,但我怀疑包含视图和对话框每个 return 它们自己的根(推测)

一个可能的解决方法是使用类似 composeTestRule.onAllNodes(isRoot()).printToLog("currentLabelExists")