Lets see in 2 minutes, why Hilt
activity for instrumentation tests is required and how to create it.
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 AppActivity
might have otherComposables
that you don’t want to create or test e.g you have bottom or drawer layout as parent container inActivity
but you want to test a specificComposable
- Usually, for testing a
Fragment
, you first launch anActivity
as container of aFragment
. so if theFragment
has annotation@AndroidEntryPoint
, the containerActivity
must also be annotated with@AndroidEntryPoint.
If you just useActivityScenario
, this doesn’t happen automatically. That’s why you need to create an activity container - Your
Composable
is depending upon aViewModel
andViewModel
is annotated with a@HiltViewModel
and in your test you want to get viewModel viahiltViewModel()
Api resolve dependencies.
How to create test container activity?
Lets go step by step
- Create
debug
folder atapp/main/src
- Create folder named
kotlin
in thatdebug
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
withexported=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