Getting Started with Compose UI Testing using Dagger Hilt

Mohit Mandalia
2 min readSep 15, 2024

--

Getting Started with Compose UI test using Dagger Hilt

Why write a UI test?

There are many reasons to write UI tests. Here are a few key ones:

  • Ensures correct UI behavior.
  • Reduces manual testing.
  • Detects bugs early.
  • Supports complex interactions.
  • Prevents regressions.

Setup Dagger Hilt for test

Add dependencies

dependencies {

androidTestImplementation("com.google.dagger:hilt-android-testing:$compose_version")
kaptAndroidTest("com.google.dagger:hilt-android-compiler:$compose_version")

}

Create HiltTestRunner class in your androidTest package

class HiltTestRunner: AndroidJUnitRunner() {
    override fun newApplication(
cl: ClassLoader?,
className: String?,
context: Context?
): Application {
return super.newApplication(cl, HiltTestApplication::class.java.name, context)
}
}

In your app’s build.gradle

android {
    defaultConfig {        //replace your package name here
testInstrumentationRunner = "com.mypackage.newapp.HiltTestRunner"
}
}

Writing simple UI Test

I already have a sample app which looks like this\

Now to start writing UI test, create a test class in your androidTest package

@HiltAndroidTest
class AddTaskTest {
    @get:Rule(order = 1)
var hiltRule = HiltAndroidRule(this)
@get:Rule(order = 2)
var rule = createAndroidComposeRule<MainActivity>()
}

We need to define two rules: HiltAndroidRule, which is required to create the Dagger component, and createAndroidComposeRule() , which helps us launch a specific activity that already has a setContentfunction defined.

Now let’s write our test function.

@Test
fun clickPlusButton_popABottomSheet() {
        rule.onNodeWithContentDescription("Add")
.performClick()
rule.onNodeWithText("Task Name")
.assertIsDisplayed()
rule.onNodeWithTag("TextFieldTaskName")
.performClick()
rule.onNodeWithTag("TextFieldTaskName")
.performTextInput("Write a UI Test")
rule.onNodeWithContentDescription("Save Task")
.performClick()
rule.onNodeWithText("Write a UI Test")
.assertIsDisplayed()
}

I am performing the following steps:

  • Clicking on a node with the content description Add.
  • Verifying if the bottom sheet is launched by checking for a component in the bottom sheet with the text hint Task Name.
  • Clicking on the TextField with the tag TextFieldTaskName and ensuring it is focused.
  • Entering the input Write a UI Test.
  • Clicking on a button with the content description Save Task.
  • Verifying if that task appears on the main screen using assertIsDisplayed().

That’s it! Congratulations, you’ve just written your first UI test.

--

--