Home > OS >  How to inject repository dagger dependency instance in my integration tests?
How to inject repository dagger dependency instance in my integration tests?

Time:02-14

I'm trying to access my repository dependency from my integration tests but I can't seem to find a way to do so.

@Singleton
@Component(
    modules = [
        RepositoryModule::class,
    ]
)
interface TestAppComponent : AppComponent {

    @Component.Builder
    interface Builder : AppComponent.Builder {

        override fun build(): TestAppComponent
    }
}

The repository module

@Module
interface RepositoryModule {

    @Binds
    fun repository(repo: Repository): IRepository
}

And in my integration test :

class AppIntegTests {

    @Inject
    lateinit var repository: IRepository

    @BeforeTest
    fun setup() {
        repository.deleteAll()
    }

    @Test
    fun testRoot() {
        withTestApplication(config) {
            handleRequest { method = HttpMethod.Get; uri = "/users" }.apply {
               assertEquals(HttpStatusCode.OK, response.status())
            }
            // tests....
        }
    }
}

When doing this, I get lateinit property has not been initialized on my injected repository. Is what I'm trying to do achievable with Dagger?

CodePudding user response:

You have to pass reference of AppIntegTests class to dagger graph in order to initialize lateinit property by dagger

Add inject function to TestAppComponent

interface TestAppComponent  {

    fun inject(test: AppIntegTests)

    @Component.Builder
    interface Builder {
        fun build(): TestAppComponent
    }
}

call this method from setUp function of AppIntegTests

class AppIntegTests {

    @Inject
    lateinit var repository: IRepository

    @Before
    fun setup() {
        val testAppComponent = DaggerTestAppComponent.builder().build()
        testAppComponent.inject(this)

        repository.deleteAll()
    }
  • Related