Kotlin Multiplatform Development Help

Testing Compose Multiplatform UI with JUnit

Compose Multiplatform for desktop provides a testing API based on JUnit and the Jetpack Compose testing API. For more details on implementation, see the Test your Compose layout guide in the Jetpack Compose documentation.

To see JUnit-based tests in action, let's start with a project generated by the Kotlin Multiplatform wizard. If you are adding tests to an existing project, you may have to replace composeApp in paths and commands with the module name you are testing (shared, for example).

Create the test source set and add the necessary dependencies:

  1. Create a directory for tests: composeApp/src/desktopTest/kotlin.

  2. In the composeApp/build.gradle.kts file, add the following dependencies:

    kotlin { //... sourceSets { //... val desktopTest by getting { dependencies { implementation(compose.desktop.uiTestJUnit4) implementation(compose.desktop.currentOs) } } } }
  3. Create a test file called ExampleTest.kt and copy the following code into it:

    import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.test.* import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.junit4.createComposeRule import org.junit.Rule import org.junit.Test class ExampleTest { @get:Rule val rule = createComposeRule() @Test fun myTest(){ // Declares a mock UI to demonstrate API calls // // Replace with your own declarations to test the code in your project rule.setContent { var text by remember { mutableStateOf("Hello") } Text( text = text, modifier = Modifier.testTag("text") ) Button( onClick = { text = "Compose" }, modifier = Modifier.testTag("button") ) { Text("Click me") } } // Tests the declared UI with assertions and actions of the JUnit-based testing API rule.onNodeWithTag("text").assertTextEquals("Hello") rule.onNodeWithTag("button").performClick() rule.onNodeWithTag("text").assertTextEquals("Compose") } }
  4. To run the test, click the run icon in the gutter next to the myTest() function or run the following command in the terminal:

    ./gradlew desktopTest

What's next?

Last modified: 06 December 2024