Unit Testing Classes with @AndroidEntryPoint Using MockK in Hilt Projects
When unit testing classes annotated with @AndroidEntryPoint in a Hilt project using MockK, you need to follow specific practices to prevent crashes when the test attempts to inject dependencies. The crashes occur because the Hilt-generated code attempts to perform dependency injection when you access @Inject annotated fields.
Setting Up the Testing Environment
To properly test classes annotated with @AndroidEntryPoint, you need to set up a Hilt testing environment:
- First, add the necessary dependencies to your build.gradle file:
// For instrumented tests
androidTestImplementation "com.google.dagger:hilt-android-testing:2.51.1"
kaptAndroidTest "com.google.dagger:hilt-android-compiler:2.51.1"
androidTestImplementation "io.mockk:mockk-android:1.12.0"
// For local unit tests
testImplementation "com.google.dagger:hilt-android-testing:2.51.1"
kaptTest "com.google.dagger:hilt-android-compiler:2.51.1"
testImplementation "io.mockk:mockk:1.12.0"
- Create a test application for Hilt:
For Robolectric tests, use the HiltTestApplication:
@HiltAndroidTest
@Config(application = HiltTestApplication::class)
class YourTest {
// Test code here
}
Approach 1: Using @HiltAndroidTest and HiltAndroidRule
This is the recommended approach for testing @AndroidEntryPoint annotated classes:
@HiltAndroidTest
class YourAndroidEntryPointClassTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
// Mock your dependencies instead of the class with @AndroidEntryPoint
@BindValue
@JvmField
val mockDependency: YourDependency = mockk(relaxed = true)
lateinit var classUnderTest: YourAndroidEntryPointClass
@Before
fun setup() {
hiltRule.inject() // This will inject the mocked dependencies
classUnderTest = YourAndroidEntryPointClass() // Instantiate the class under test
}
@Test
fun testYourMethod() {
// Arrange
every { mockDependency.someMethod() } returns "mocked result"
// Act
val result = classUnderTest.methodThatUsesDependency()
// Assert
assertEquals("expected result", result)
verify { mockDependency.someMethod() }
}
}
Approach 2: Replace Bindings with Test Modules
If you need to mock multiple dependencies, you can create a test module:
@UninstallModules(YourProductionModule::class)
@HiltAndroidTest
class YourAndroidEntryPointClassTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
@Module
@InstallIn(SingletonComponent::class)
object TestModule {
@Provides
@Singleton
fun provideYourDependency(): YourDependency {
return mockk(relaxed = true)
}
}
@Inject
lateinit var classUnderTest: YourAndroidEntryPointClass
@Before
fun setup() {
hiltRule.inject()
}
@Test
fun testYourMethod() {
// Test implementation
}
}
Approach 3: Using @BindValue for Direct Mocking
The @BindValue annotation is particularly useful for providing mock implementations:
@UninstallModules(YourProductionModule::class)
@HiltAndroidTest
class YourAndroidEntryPointClassTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
@BindValue
@JvmField
val dependency1: Dependency1 = mockk(relaxed = true)
@BindValue
@JvmField
val dependency2: Dependency2 = mockk(relaxed = true)
@Inject
lateinit var classUnderTest: YourAndroidEntryPointClass
@Before
fun setup() {
hiltRule.inject()
}
@Test
fun testSomeFunction() {
// Configure mocks
every { dependency1.someMethod() } returns "mocked value"
// Execute method under test
val result = classUnderTest.methodToTest()
// Verify
verify { dependency1.someMethod() }
assertEquals("expected result", result)
}
}
Avoiding Common Issues
-
Don't mock the @AndroidEntryPoint class directly:
// INCORRECT approach
val myActivity = mockk<myactivity>() // This will cause issues
// CORRECT approach
// Use Hilt to create the real instance and mock its dependencies instead
-
For components like activities or fragments:
If you're testing activities or fragments with @AndroidEntryPoint, consider using ActivityScenario or FragmentScenario with Hilt:
@HiltAndroidTest
class MyActivityTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
@BindValue
@JvmField
val mockRepository: MyRepository = mockk(relaxed = true)
@Before
fun setup() {
hiltRule.inject()
}
@Test
fun testSomething() {
// Configure your mockRepository
every { mockRepository.getData() } returns listOf("test data")
// Launch the activity
val scenario = ActivityScenario.launch(MyActivity::class.java)
// Verify behavior
scenario.onActivity { activity ->
// Assertions on the activity
}
}
}
-
For ViewModels with @HiltViewModel:
@HiltAndroidTest
class MyViewModelTest {
@get:Rule
var hiltRule = HiltAndroidRule(this)
@BindValue
@JvmField
val mockRepository: MyRepository = mockk(relaxed = true)
@Inject
lateinit var viewModel: MyViewModel
@Before
fun setup() {
hiltRule.inject()
}
@Test
fun testViewModelMethod() {
// Configure mocks and test the ViewModel
}
}
Pre-Android Pie (API 28) Considerations
If your app supports devices running Android versions below API 28 (Android 9 Pie), there are limitations with MockK for mocking final classes. For this case, you have two options:
- Use Dexopener as recommended by MockK
- Use the all-open Kotlin compiler plugin which is more lightweight[4]
By following these approaches, you can effectively unit test classes annotated with @AndroidEntryPoint in your Hilt project without experiencing crashes when accessing @Inject annotated variables.