0
0
Android Kotlinmobile~5 mins

Compose UI testing in Android Kotlin

Choose your learning style9 modes available
Introduction

Compose UI testing helps you check if your app's screen looks and works right. It makes sure buttons, texts, and other parts behave as expected.

You want to check if a button click changes the screen correctly.
You want to verify that a text label shows the right message.
You want to test if a list displays the correct items.
You want to make sure your UI works well after changes.
You want to catch bugs before users see them.
Syntax
Android Kotlin
createComposeRule().apply {
  onNodeWithText("Button Text").performClick()
  onNodeWithText("Result Text").assertIsDisplayed()
}

createComposeRule() sets up the test environment for Compose UI.

onNodeWithText() finds UI elements by their visible text.

Examples
Clicks a button or element with text "Click Me".
Android Kotlin
composeTestRule.onNodeWithText("Click Me").performClick()
Checks if the text "Hello World" is visible on the screen.
Android Kotlin
composeTestRule.onNodeWithText("Hello World").assertIsDisplayed()
Finds a UI element by a test tag and checks it exists.
Android Kotlin
composeTestRule.onNodeWithTag("myButton").assertExists()
Sample App

This test shows a button labeled "Say Hello". When clicked, it shows the text "Hello!". The test clicks the button and checks if the greeting text appears.

Android Kotlin
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.*
import org.junit.Rule
import org.junit.Test

class MyComposeTest {
  @get:Rule
  val composeTestRule = createComposeRule()

  @Composable
  fun GreetingButton() {
    var clicked = false
    Button(onClick = { clicked = true }) {
      Text("Say Hello")
    }
    if (clicked) {
      Text("Hello!")
    }
  }

  @Test
  fun testGreetingButton() {
    composeTestRule.setContent {
      GreetingButton()
    }
    composeTestRule.onNodeWithText("Say Hello").assertIsDisplayed()
    composeTestRule.onNodeWithText("Say Hello").performClick()
    composeTestRule.onNodeWithText("Hello!").assertIsDisplayed()
  }
}
OutputSuccess
Important Notes

Use onNodeWithText to find elements by visible text.

Use performClick() to simulate user taps.

Use assertIsDisplayed() to check if UI elements are visible.

Summary

Compose UI testing helps check your app's screens work as expected.

Use createComposeRule() to set up tests.

Find UI elements by text or tags, then perform actions or checks.