Android Hilt Test — Complete Guide
In this tutorial, you'll learn about Android Hilt Test. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your instrumentation tests crash because Hilt can't find the test module, or you can't replace a real dependency with a mock in tests.
Wrong Approach ❌
// No @HiltAndroidTest — test doesn't have Hilt setup
class MyTest {
@get:Rule val hiltRule = HiltAndroidRule(this) // Fails!
@Test fun testSomething() { }
}
// Trying to replace a binding without a test module
@HiltAndroidTest
class BadTest {
@Inject lateinit var repository: UserRepository // Real impl!
}
Output: HiltAndroidRule initialisation fails. Real dependencies in tests.
Right Approach ✅
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class UserRepositoryTest {
@get:Rule
val hiltRule = HiltAndroidRule(this)
@Inject
lateinit var repository: UserRepository
@Before
fun setUp() {
hiltRule.inject() // Inject dependencies
}
@Test
fun testRepository() = runTest {
val result = repository.getUser("1")
assertEquals("Alice", result.name)
}
}
// Test module replaces real impl with mock/fake
@Module
@TestInstallIn(
components = [SingletonComponent::class],
replaces = [RealRepositoryModule::class]
)
object TestRepositoryModule {
@Provides
@Singleton
fun provideRepository(): UserRepository = FakeRepository()
}
// For ViewModel tests
@HiltAndroidTest
class UserViewModelTest {
@Inject lateinit var viewModel: UserViewModel
@Test
fun testLoadUsers() {
// ViewModel uses fake repository from test module
}
}
Output: Tests run with fake dependencies via @TestInstallIn.
Prevention
- Annotate all Hilt tests with
@HiltAndroidTest. - Call
hiltRule.inject()in@Before. - Use
@TestInstallInwithreplacesfor module substitution. - For unit tests, use
@HiltViewModeldirectly without@HiltAndroidTest.
Common Mistakes with hilt test
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro