Why to create Hilt Container Activity for Instrumentation Tests

Saqib
2 min readFeb 13, 2023

--

Lets see in 2 minutes, why Hilt activity for instrumentation tests is required and how to create it.

Photo by Erda Estremera on Unsplash

Hilt makes testing easier, You do not need to always create a separate activity for test unless its really required.

Possible scenarios for test activity

There are different situations where you want to create a separate activity for test e.g the following reasons but not limited to these.

  • You want to test a Composable But your App Activity might have other Composables that you don’t want to create or test e.g you have bottom or drawer layout as parent container in Activity but you want to test a specific Composable
  • Usually, for testing a Fragment, you first launch an Activity as container of a Fragment. so if the Fragment has annotation @AndroidEntryPoint, the container Activity must also be annotated with @AndroidEntryPoint. If you just use ActivityScenario, this doesn’t happen automatically. That’s why you need to create an activity container
  • Your Composable is depending upon a ViewModel and ViewModel is annotated with a @HiltViewModel and in your test you want to get viewModel via hiltViewModel() Api resolve dependencies.

How to create test container activity?

Lets go step by step

  • Create debug folder at app/main/src
  • Create folder named kotlin in that debug folder
  • Create package named as your app package name e.g com.name1.name2
  • Now Create activity inside that folder HiltTestActivity and annotate it with @AndroidEntryPoint
  • You need to add this activity into Android Manifest with exported=false For that you need to add following dependency
debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"

AndroidManifest.xml file will looks like this

Project structure will look like this

How to use in test?

First have to create test rule using HiltTestActivity and then set activity content to your Composable that you want to test.

Now setup the Test as below.

Now you can use composeTestRule to perform test on your Composable

That's it!

You can download the project from here

Other stories in test series

--

--

Saqib

Senior Mobile Engineer (Android & iOS) , Berlin | Sharing my development experience