I have composable function winch just transform one object to another (state). Here is my code:
@Composable
fun Walpaper.toMaterialState(): MaterialState {
return MaterialState(
price = if (isVip) vipPrice else price,
number = number.substring(4),
)
}
And I'm trying to write test for my composable function.
@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
}
I get error @Composable invocations can only happen from the context of a @Composable function
How can i fix this error, please help me.
You can either run android instrumentation test which runs on android device, or use robolectric to test your composable in JVM.
In both cases you need something more than JUnit to test your composable. Since compose requires android dependencies.
we have to either provide the android dependencies by running the app in device or use robolectric to simulate the android dependencies in JVM.
Dependencies
androidTestImplementation("androidx.compose.ui:ui-test-junit4:$compose_version")
debugImplementation("androidx.compose.ui:ui-test-manifest:$compose_version")
Test : This goes in androidTest folder
class MyComposeTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun myTest() {
// Start the app
composeTestRule.setContent {
val wallpaper = createWallpaper()
}
// Do assertion
composeTestRule.onNodeWithText("Continue").performClick()
}
}
Dependencies
testImplementation "junit:junit:4.13.2"
testImplementation "org.robolectric:robolectric:4.10.3"
Test code : This goes in test folder
@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()
}
}
I have repo that showcase various testing in android. Please do take a look at it for more concrete example
https://github.com/sridhar-sp/android-test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With