Android Compose LaunchedEffect 延迟卡在仪器测试中

问题描述 投票:0回答:0

我使用组合导航实现了自定义简单启动画面。为了在短时间内导航到主屏幕,我使用了

LaunchedEffect
delay
里面。它工作正常。但是在 UI 测试中,
LaunchedEffect
中的调用停留在
delay
。 这是例子:

@Composable
private fun Navigation() {
    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = "splash") {
        composable("splash") {
            SplashScreen {
                navController.navigate("main") {
                    popUpTo("splash") {
                        inclusive = true
                    }
                }
            }
        }
        composable("main") { MainScreen() }
    }
}

@Composable
private fun SplashScreen(
    onComplete: () -> Unit,
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black)
    )

    val currentOnComplete by rememberUpdatedState(onComplete)
    LaunchedEffect(Unit) {
        delay(200)
        currentOnComplete()
    }
}

@Composable
private fun MainScreen() {
    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White),
    ) {
        Text("Main Screen")
    }
}
@Test
fun testMainScreen() {
    onView(isRoot()).perform(waitFor(2000))
    composeTestRule.onNodeWithText("Main Screen").assertIsDisplayed()
}

我想出的唯一解决方案是使用

ViewModel
并在
delay
中使用
viewModelScope
。但是通过这种方式,我破坏了使用导航显示启动画面的整个想法。

android android-jetpack-compose android-testing android-instrumentation
© www.soinside.com 2019 - 2024. All rights reserved.