Ask Your Question
1

How can I obtain a viewmodel when using hilt in UnitTest?

asked 2022-09-23 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-06-17 00:00:00 +0000

lalupa gravatar image

To obtain a viewmodel when using Hilt in UnitTest, you can use the HiltRule class provided by Hilt. Here are the steps:

  1. Add the dependencies for Hilt and Hilt testing in your project as follows:
dependencies {
    // Hilt
    implementation 'com.google.dagger:hilt-android:2.38.1'
    kapt 'com.google.dagger:hilt-android-compiler:2.38.1'
    // Hilt testing
    testImplementation 'com.google.dagger:hilt-android-testing:2.38.1'
    androidTestImplementation 'com.google.dagger:hilt-android-testing:2.38.1'
    kaptTest 'com.google.dagger:hilt-android-compiler:2.38.1'
}
  1. Create a test class and annotate it with @HiltAndroidTest.
@HiltAndroidTest
class MyViewModelTest {
    // ...
}
  1. In your test class, create an instance of HiltViewModelTest and get the viewmodel you want to test.
@get:Rule
var hiltRule = HiltViewModelTestRule()

@Test
fun testMyViewModel() {
    val viewModel = hiltRule.viewModel<MyViewModel>()
    // Use the viewModel methods to test the behavior
}
  1. Use the viewModel method provided by HiltViewModelTestRule to get the viewmodel instance. You can now use it to test the behavior of the viewmodel.

Note: You need to add the Hilt components to the test module or use the @UninstallModules annotation to remove any component that may interfere with your test.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-23 11:00:00 +0000

Seen: 12 times

Last updated: Jun 17 '22