Mastering Hilt - Android | Kotlin | Hilt (Dagger 2) [Part 9]

Mastering Hilt - Android | Kotlin | Hilt (Dagger 2) [Part 9]

Becoming Proficient in Dependency Injection with Hilt for Android (Kotlin)

ยท

2 min read

Table of contents

Testing with Hilt

Testing with Hilt involves using different approaches to manage dependencies and test components effectively. Here are two techniques for testing with Hilt:

Testing with @UninstallModules:

The @UninstallModules annotation is used in Hilt Android tests to remove specific modules from the test component. This is helpful when we want to replace or remove certain bindings during testing.

Example - Testing with @UninstallModules:

Assuming we have a module like this:

@Module
@InstallIn(ApplicationComponent::class)
object MyModule {
    @Singleton
    @Provides
    fun provideMyDependency(): MyDependency {
        return MyDependencyImpl()
    }
}

In our test class, we can use @UninstallModules to uninstall the MyModule during testing:

@HiltAndroidTest
@UninstallModules(MyModule::class)
class MyActivityTest {
    // Our test methods here
}

By using @UninstallModules, Hilt will remove MyModule from the test component and we can replace it with a test module or use Hilt's default bindings.

Custom Test Components:

Custom test components allow us to create a separate Hilt component for testing with custom bindings. This is beneficial when we need to replace some dependencies with mock implementations during testing.

Example - Creating a Custom Test Component:

Assuming we have a module and a custom test component like this:

@Module
@InstallIn(ApplicationComponent::class)
object MyModule {
    @Singleton
    @Provides
    fun provideMyDependency(): MyDependency {
        return MyDependencyImpl()
    }
}

@CustomTestComponent
@Singleton
@Component(modules = [TestModule::class])
interface TestAppComponent : AndroidInjector<MyApplication> {
    @Component.Factory
    interface Factory : AndroidInjector.Factory<MyApplication>
}

@Module
@InstallIn(ApplicationComponent::class)
object TestModule {
    @Singleton
    @Provides
    fun provideMyDependency(): MyDependency {
        return MyMockDependency()
    }
}

In this example, we have a TestModule provides a mock implementation of MyDependency. We also define a custom test component TestAppComponent, which uses the TestModule instead of the original MyModule.

To use the custom test component in our test class, we can annotate the test class with @CustomTestComponent:

@HiltAndroidTest
@CustomTestComponent
class MyActivityTest {
    // Our test methods here
}

By using a custom test component, we can provide custom dependencies for testing, such as mock implementations, and ensure that our tests are isolated from the actual implementation of the dependencies.

Testing with Hilt allows us to seamlessly manage dependencies and create more maintainable and reliable tests for our Android application.

ย