Ponder Guy
Ponder Guy

Reputation: 31

Dagger Inject for Integration Tests

So up to Dagger 2.11 I've been able to construct TestComponent's and Modules to enable key components to be injected into integration tests. This is great for Api tests and objects with heavy component requirements

Typically I would have code like this:-

class SpotifyApiTest  {

    lateinit var spotifyApi : SpotifyApi
        @Inject set
    lateinit var spotifyHelper : SpotifyIOHelper
        @Inject set

@Before
fun setup() {
    var context = InstrumentationRegistry.getInstrumentation().context

    val testAppComponent = DaggerSpotifyTestComponent.builder()
            .spotifyApiModule(SpotifyApiModule(context))
            .build()
    testAppComponent.inject(this)

}

@Test
  ......
}

N/B remember to add the following to your gradle build file

kaptAndroidTest "com.google.dagger:dagger-compiler:$daggerVersion"

This approach works extremely well up to Dagger 2.11 but after that version Modules with parameterized constructors do not work preventing context being supplied let alone the application. So how can I use the new AndroidInjection() functionality for integration tests with the Dagger 2.16 for example?

Upvotes: 2

Views: 631

Answers (1)

Ponder Guy
Ponder Guy

Reputation: 31

I've come up with the following approach to inject the context into the modules for dagger 2.11+ so its a start, I've still no idea how to handle application from the integration test perspective.

@Singleton
@Component(modules = arrayOf(SpotifyAccountsModule::class,SpotifyApiModule::class))
interface SpotifyTestComponent {
    fun inject(test: SpotifyApiTest)
    fun inject(test: SpotifyAccountApiTest)

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun create(context: Context): Builder
        fun build(): SpotifyTestComponent
    }
}

This will make context available as a parameter for providers and should help others when they reach this particular brick wall.

Upvotes: 1

Related Questions