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.
First approach : compose instrumentation testing
Dependencies
Test : This goes in androidTest folder
Second approach : compose robo-electric test
Dependencies
Test code : This goes in test folder
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