Testing Jetpack Compose

@Composable
fun MyComponent(viewModel: MyViewModel) {
Text(if(viewModel.someBool) "Hello" else "World"
}
testImplementation 'org.robolectric:robolectric:4.8.1'
testImplementation 'androidx.compose.ui:ui-test-junit4:1.1.1'
debugImplementation 'androidx.compose.ui:ui-test-manifest:1.1.1'
@RunWith(RobolectricTestRunner::class)
@Config(application = MyTestApplication::class,
sdk = [28],
instrumentedPackages = [
"androidx.loader.content"
])
abstract class MyComposeTest {
@get:Rule
val composeTestRule: createComposeTestRule()
@Before
open fun setup() {
MockKAnnotations.init(this)
}
}
class MyTest: MyComposeTest() {
@RelaxedMockK
private lateinit var mockViewModel: MyViewModel
@Test
helloIsDisplayed() {
every { mockViewModel.someBool } returns true
composeTestRule.setContent {
MyComponent(mockViewModel)
}
composeTestRule.onNodeWithText("Hello").assertExists()
}
@Test
worldIsDisplayed() {
every { mockViewModel.someBool } returns false
composeTestRule.setContent {
MyComponent(mockViewModel)
}
composeTestRule.onNodeWithText("World").assertExists()
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store