我有一个
Composable
,它有一个 Text
和 Button
。如果当前方向是纵向,Text
将显示 P
,否则显示 L
。单击 Button
会将方向更改为横向,(因此之后,应该将文本从 P
更改为 L
)
这是可组合的
@Composable
fun MyApp() {
val currentOrientation = LocalConfiguration.current.orientation
val orientation = if (currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
"P"
} else {
"L"
}
val activity = LocalContext.current as Activity
Column {
Text(text = orientation)
Button(onClick = {
// change orientation to landscape
activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}) {
Text(text = "DO IT")
}
}
}
这是我的测试方法
@get:Rule
val composeRule = createComposeRule()
@Test
fun test() {
composeRule.setContent { MyApp() }
// Starts with portrait
composeRule.onNodeWithText("P").assertIsDisplayed()
// Change the orientation to Landscape
composeRule.onNodeWithText("DO IT").performClick()
// Now the text should be `L`
composeRule.onNodeWithText("L").assertIsDisplayed()
}
但是当我运行测试查看文本是否更新时,出现以下错误。 (手动测试有效)
java.lang.IllegalStateException: No compose views found in the app. Is your Activity resumed?
at androidx.compose.ui.test.TestContext.getAllSemanticsNodes$ui_test_release(TestOwner.kt:96)
at androidx.compose.ui.test.SemanticsNodeInteraction.fetchSemanticsNodes$ui_test_release(SemanticsNodeInteraction.kt:82)
at androidx.compose.ui.test.SemanticsNodeInteraction.fetchOneOrDie(SemanticsNodeInteraction.kt:155)
at androidx.compose.ui.test.SemanticsNodeInteraction.assertExists(SemanticsNodeInteraction.kt:147)
at androidx.compose.ui.test.SemanticsNodeInteraction.assertExists$default(SemanticsNodeInteraction.kt:146)
如果您想自己尝试的话,这是完整的测试文件。
问题
测试时屏幕亮着吗?
就我而言,只需关闭屏幕即可轻松重现。请注意,我使用的是模拟器。
执行点击事件时我遇到了同样的问题。 当我使用我的设备进行测试时,当您的测试设备/模拟器的屏幕未唤醒(关闭)时发生。
我的解决办法就是打开屏幕。
如果您在物理设备上运行测试,请确保手机已解锁并且屏幕已打开。