Title: Jetpack Compose instrument test with @HiltViewModel
Tags: android;kotlin;android-jetpack-compose;dagger-hilt
Question: So I want to test my jetpack compose project. It's easy enough running an instrument test following [these instructions]1 on android dev site, but when you add @HiltViewModel injection into the combination things get complicated.
I'm trying to test a pretty simple compose screen with a ViewModel that has an @Inject constructor.
The screen itself looks like this:
@Composable
fun LandingScreen() {
val loginViewModel: LoginViewModel = viewModel()
MyTheme {
Surface(color = MaterialTheme.colors.background) {
val user by loginViewModel.user.observeAsState()
if (user != null) {
MainScreen()
} else {
LoginScreen(loginViewModel)
}
}
and this is the view model:
@HiltViewModel
class LoginViewModel @Inject constructor(private val userService: UserService) : ViewModel() {
val user = userService.loggedInUser.asLiveData()
User service is of course backed by a room database and the loggedInUser property returns a Flow.
Things work as expected on standard run but when trying to run it in an instrument test it can't inject the view model.
@HiltAndroidTest
class LandingScreenTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
@get:Rule
val composeTestRule = createComposeRule()
@Inject
lateinit var loginViewModel: LoginViewModel
@Before
fun init() {
hiltRule.inject()
@Test
fun MyTest() {
composeTestRule.setContent {
MyTheme {
LandingScreen()
}
}
composeTestRule.onNodeWithText(&quot;Welcome&quot;).assertIsDisplayed()
Injection of an @HiltViewModel class is prohibited since it does not
create a ViewModel instance correctly.   Access the ViewModel via the
Android APIs (e.g. ViewModelProvider) instead.   Injected ViewModel:
com.example.viewmodels.LoginViewModel
How do you make that work with the ViewModelProvider instead of the @HiltViewModel?
Comment: Did you find any solution?

Comment: https://github.com/google/dagger/issues/2318 might give you answers

Comment: @Chait Unfortunately not. I had to park it for now.


Here is another answer: You must annotate any UI test that uses Hilt with @HiltAndroidTest. This annotation is responsible for generating the Hilt components for each test.
https://developer.android.com/training/dependency-injection/hilt-testing
Comment for this answer: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

Here is another answer: Try to do something like this:
@HiltAndroidTest
class LandingScreenTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
@get:Rule
val composeTestRule = createComposeRule()
// Remove this line @Inject
lateinit var loginViewModel: LoginViewModel
@Before
fun init() {
hiltRule.inject()
@Test
fun MyTest() {
composeTestRule.setContent {
loginViewModel= hiltViewModel() // Add this line
MyTheme {
LandingScreen()
}
}
composeTestRule.onNodeWithText(&quot;Welcome&quot;).assertIsDisplayed()

Here is another answer: Hilt needs an entry point to inject fields. In this case that would probably be an Activity annotated with @AndroidEntryPoint. You can use your MainActivity for that, but that would mean that you would then have to add code to every test to navigate to the desired screen which could be tedious depending on the size of your app, and is not feasible if your project is multimodule and your current Test file does not have access to MainActivity. Instead, you could create a separate dummy Activity whose sole purpose is to host your composable (in this case LoginScreen) and annotate it with @AndroidEntryPoint. Make sure to put it into a debug directory so it's not shipped with the project. Then you can use createAndroidComposeRule<Activity&gt;() to reference that composable. You dont need to inject the ViewModel directly so get rid of that line too.
In the end your Test File should look like this:
@HiltAndroidTest
class LandingScreenTest {
@get:Rule(order = 0)
val hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1)
val composeRule = createAndroidComposeRule<LoginTestActivity&gt;()
@Before
fun init() {
hiltRule.inject()
@Test
fun MyTest() {
composeTestRule.onNodeWithText(&quot;Welcome&quot;).assertIsDisplayed()
And your your dummy activity can look like this:
@AndroidEntryPoint
class LoginTestActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LoginScreen()
}
And the debug directory would look like this:debug directory with dummy activity
Yes the debug directory has its own manifest and that is where you should add the dummy activity. set exported to false.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 3, 'CommentCount': 3, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:08/18/21', 'FavoriteCount': 3.0, 'PostTypeId': 1, 'Tags': '<android><kotlin><android-jetpack-compose><dagger-hilt>', 'Title': 'Jetpack Compose instrument test with @HiltViewModel', 'ViewCount': 1550, 'id': 68826881, 'user_AboutMe': '', 'user_AccountId': 5726463.0, 'user_DisplayName': 'Vahid', 'user_Reputation': 1639.0, 'user_Views': 85.0, 'user_id': 5724584.0}}