如何在我的集成测试中注入存储库匕首依赖实例?

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

我正在尝试从我的集成测试访问我的存储库依赖项,但我似乎找不到这样做的方法。

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

    @Component.Builder
    interface Builder : AppComponent.Builder {

        override fun build(): TestAppComponent
    }
}

存储库模块

@Module
interface RepositoryModule {

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

在我的集成测试中:

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....
        }
    }
}

执行此操作时,我在注入的存储库中得到 lateinit property has not been initialized。 我想用 Dagger 实现的目标是什么?

您必须将 AppIntegTests class 的引用传递给 dagger graph 才能通过 dagger 初始化 lateinit 属性

inject功能添加到TestAppComponent

interface TestAppComponent  {

    fun inject(test: AppIntegTests)

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

AppIntegTests

setUp 函数调用此方法
class AppIntegTests {

    @Inject
    lateinit var repository: IRepository

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

        repository.deleteAll()
    }