我有可组合功能绞盘,只需将一个对象转换为另一个对象(状态)。这是我的代码:
@Composable
fun Walpaper.toMaterialState(): MaterialState {
return MaterialState(
price = if (isVip) vipPrice else price,
number = number.substring(4),
)
}
我正在尝试为我的可组合函数编写测试。
@Test
fun `test convert to material state`() {
val = walpaper = createWalpaper()
val state = walpaper.toMaterialState() // error @Composable invocations can only happen from the context of a @Composable function
}
我收到错误 @Composable 调用只能在 @Composable 函数的上下文中发生
我该如何修复这个错误,请帮助我。
您可以运行在 Android 设备上运行的 Android Instrumentation 测试,或者使用 robolectric 在 JVM 中测试您的可组合项。
在这两种情况下,您都需要 JUnit 以外的东西来测试您的可组合项。由于 compose 需要 android 依赖。
我们必须通过在设备中运行应用程序来提供 android 依赖项,或者使用 robolectric 在 JVM 中模拟 android 依赖项。
依赖关系
androidTestImplementation("androidx.compose.ui:ui-test-junit4:$compose_version")
debugImplementation("androidx.compose.ui:ui-test-manifest:$compose_version")
测试:这位于 androidTest 文件夹中
class MyComposeTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun myTest() {
// Start the app
composeTestRule.setContent {
val wallpaper = createWallpaper()
}
// Do assertion
composeTestRule.onNodeWithText("Continue").performClick()
}
}
依赖关系
testImplementation "junit:junit:4.13.2"
testImplementation "org.robolectric:robolectric:4.10.3"
测试代码:这位于测试文件夹中
@RunWith(RobolectricTestRunner::class)
class ProfileTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun testCase() {
// Start the app
composeTestRule.setContent {
val wallpaper = createWallpaper()
}
// Do assertion
composeTestRule.onNodeWithText("Continue").performClick()
}
}
我有repo展示了android中的各种测试。请看一下更具体的例子