skip to content

In Hilt instrumented tests, how do you swap the production network module for a fake, and when is @UninstallModules better than @TestInstallIn?

level: seniorimportance: should knowfreq 55%

answer

  1. a test annotation and a rule
  2. a test application via the runner
  3. replace the module, not the class
  4. whole source set versus one class
  5. per-class components cost build time

basics

~20 s

Mark the test @HiltAndroidTest, run HiltAndroidRule first on HiltTestApplication, and add an androidTest module annotated @TestInstallIn that replaces the network module. Use @UninstallModules with a nested module or @BindValue only when one test class needs a different fake.

solid answer

~40 s

A Hilt UI test is annotated `@HiltAndroidTest` and holds a `HiltAndroidRule(this)` that runs before any activity or Compose rule; a custom `AndroidJUnitRunner` makes the instrumentation start `HiltTestApplication`. To swap the network layer for every test, add a module to `androidTest` with `@TestInstallIn(components = [SingletonComponent::class], replaces = [NetworkModule::class])` that provides a fake `NewsApi`; every test in that source set then gets the fake. When a single test class needs something different, annotate it `@UninstallModules(NetworkModule::class)` and supply the binding with a nested `@InstallIn` module or a `@BindValue` field. Prefer `@TestInstallIn`: `@UninstallModules` and `@BindValue` force Hilt to generate separate components for that class, which slows test builds, and a `@TestInstallIn` module cannot itself be uninstalled.

code

kotlin · 26 lines
kotlin
@Module
@TestInstallIn(
    components = [SingletonComponent::class],
    replaces = [NetworkModule::class]
)
object FakeNetworkModule {
    @Provides
    @Singleton
    fun provideNewsApi(): NewsApi = FakeNewsApi()
}

@HiltAndroidTest
class HeadlinesScreenTest {
    @get:Rule(order = 0)
    val hiltRule = HiltAndroidRule(this)

    @get:Rule(order = 1)
    val composeRule = createAndroidComposeRule<HiltTestActivity>()

    @Inject lateinit var repository: NewsRepository

    @Before
    fun setUp() {
        hiltRule.inject()
    }
}

go deeper

for a junior

Recall @HiltAndroidTest, HiltAndroidRule and HiltTestApplication, and that plain unit tests construct classes directly without Hilt.

for a middle

Explain how @TestInstallIn replaces a production module for a whole source set, and the setup steps: rule order, test runner and hiltRule.inject().

for a senior

Choose between @TestInstallIn and @UninstallModules with @BindValue, knowing the per-class component cost and the whole-module replacement rule.

for a principal

Shape production modules so each layer can be faked by one test module, and set a team default that keeps test build times flat.

## When Hilt is needed in a test at all For a **unit test** of a class with an `@Inject` constructor, Hilt is unnecessary: call the constructor with fakes. The same goes for a ViewModel. Hilt earns its place in **integration and UI tests**, where an activity or a screen is launched and the whole graph has to be assembled the way production assembles it, minus the parts you want to fake. Each test runs against fresh component instances, so graph state never leaks from one test to the next. ## Setting up an instrumented Hilt test 1. Add `hilt-android-testing` to `androidTestImplementation` and the Hilt compiler to the matching processor configuration; for Robolectric, the `test` equivalents. 2. Annotate the test class with **`@HiltAndroidTest`**, which tells Hilt to generate components for it. 3. Add **`HiltAndroidRule(this)`** and make it run **first**, with `@get:Rule(order = 0)` or as the outer rule of a `RuleChain`. It manages the test's component state, which must be ready before an activity under test is injected. 4. Run the tests in **`HiltTestApplication`**: write a runner extending `AndroidJUnitRunner` that overrides `newApplication` to pass `HiltTestApplication::class.java.name`, and point `testInstrumentationRunner` at it. Robolectric uses `@Config(application = HiltTestApplication::class)` or `robolectric.properties`. If the app needs a custom base application, `@CustomTestApplication` generates one. 5. For Compose tests, create an empty `@AndroidEntryPoint` activity in `androidTest`, conventionally `HiltTestActivity`, to host content. 6. To inject into the test itself, declare `@Inject lateinit var` fields and call **`hiltRule.inject()`**, typically in `@Before`. ## Replacing the network module for every test: `@TestInstallIn` The news app's production `NetworkModule` provides the OkHttp client and the Retrofit `NewsApi`. A UI test must not hit the network, so it needs a fake `NewsApi`. - Create a module in the `androidTest` (or `test`) source set annotated `@Module` and **`@TestInstallIn(components = [...], replaces = [...])`**. `replaces` lists the production `@InstallIn` modules it stands in for, and `components` names where it is installed. - Every test in that source set is now built with the fake; nothing changes in production code. - Replacement works on **modules, not individual bindings**: everything the replaced module provided disappears, so the fake module must provide every binding the tests still need from it. This is one reason to keep network bindings in their own small module. ## Replacing for one test class: `@UninstallModules` and `@BindValue` When one test needs a different fake, for instance an API that always fails: - Annotate the class with **`@UninstallModules(NetworkModule::class)`**, then supply the binding with a **nested `@Module @InstallIn(...)`** class inside the test, or with a **`@BindValue`** field such as `@BindValue val newsApi: NewsApi = FailingNewsApi()`. - `@BindValue` binds the field's value into `SingletonComponent` under the field's type and qualifiers, which makes the fake both injected and directly reachable from the test. `@BindValueIntoSet` and `@BindValueIntoMap` contribute to multibindings instead. - `@UninstallModules` can only remove `@InstallIn` modules. Naming a `@TestInstallIn` module is a compile error, and a module pulled in through another module's `includes` cannot be removed until the including module is removed too. ## The build-time trade-off | | `@TestInstallIn` | `@UninstallModules` (+ nested module / `@BindValue`) | |---|---|---| | Applies to | every test in the source set | one test class | | Generated component code | shared between tests | a dedicated set for that class | | Build cost | low | grows with each such class | | Typical use | the standard fake for a layer | one-off scenarios | By default, Hilt lets tests that define no `@BindValue` fields or nested modules **share** generated component code, which cuts compile work. A class that uninstalls modules or binds its own values gets its own components, and the Android guide warns this can significantly affect build times. Hence the guidance: use `@TestInstallIn` wherever the fake is the norm, and save `@UninstallModules` for genuine exceptions. ## Special cases - **A custom base application**: if the test application must extend your own base class, annotate a class or interface with `@CustomTestApplication(BaseApplication::class)`; Hilt generates an application named after it with an `_Application` suffix, which the runner then starts. - **An entry point needed before the test's singleton component exists**, for example from code that runs while the test application is being created: annotate it `@EarlyEntryPoint` and read it with `EarlyEntryPoints.get()`. Reading such an interface with the ordinary `EntryPoints.get()` in a test fails with an explicit error. - **Robolectric**: the same annotations and rule apply; only the way the test application is selected differs. ## Mistakes that break Hilt tests - Letting another rule run before `HiltAndroidRule`. - Forgetting `hiltRule.inject()`, leaving `@Inject` test fields uninitialized. - Launching the test without `HiltTestApplication`, so no Hilt application exists. - Replacing a module whose other bindings the app still needs, then chasing missing-binding errors.

  • Your fake module replaces NetworkModule, and now a test fails with a missing OkHttpClient binding; why?
    `@TestInstallIn` replaces the whole module, so every binding `NetworkModule` declared is gone, including the client something else still injects. Either provide that binding in the fake module too, or split the production module so the part you fake stands alone.
  • How does @BindValue differ from a nested @InstallIn module in a test?
    `@BindValue` binds a test field's current value into `SingletonComponent` under its type and qualifiers, so the test holds the very instance the app receives and can configure or verify it. A nested module declares a binding with code. Either needs the production module uninstalled when it binds the same type.

  • Unit-testing a class with an @Inject constructor requires HiltAndroidRule.
  • @UninstallModules can remove a module declared with @TestInstallIn.
  • @TestInstallIn replaces a single binding and leaves the module's others in place.
  • HiltAndroidRule can run after the activity or Compose rule.
  • @UninstallModules on many classes has no effect on build time.
  • Test @Inject fields are filled automatically without calling hiltRule.inject().