'How to write Unit Testing with Dagger 2 Subcomponent
I'm just starting to use Dagger 2 in my Android application, And I'm trying to write Unit Tests that their Modules are defined as Subcomponents.
I've read Google's post about Testing with Dagger. And this very helpful Medium post as well. But I only found examples on how to test with Components but not Subcomponents. And I can't seem to get it to work.
Solution 1:[1]
Separate injector/provider methods from Component interface.
This is for example:
@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {
fun uploadComponent(module: UploadModule): UploadComponent
}
@Subcomponent(modules = [UploadModule::class])
interface UploadComponent : UploadInjector {
}
interface UploadInjector {
fun inject(it: UploadWorker)
}
And then you can introduce UploadInjector to production code regardless whether it instantiated with production or test environment.
@Singleton
@Component(modules = [TestAppModule::class])
interface TestAppComponent {
fun uploadComponent(module: TestUploadModule): TestUploadComponent
}
@Subcomponent(modules = [TestUploadModule::class])
interface TestUploadComponent : UploadInjector {
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kenjiuno |
