gpt4 book ai didi

android - 用于集成测试的 Dagger Inject

转载 作者:行者123 更新时间:2023-11-28 20:36:46 24 4
gpt4 key购买 nike

在 Dagger 2.11 之前,我已经能够构建 TestComponent 和模块来将关键组件注入(inject)到集成测试中。这对于 Api 测试和具有大量组件要求的对象非常有用

通常我会有这样的代码:-

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"

这种方法在 Dagger 2.11 之前工作得非常好,但在那个版本之后,带有参数化构造函数的模块不再工作,阻止提供上下文,更不用说应用程序了。那么如何使用新的 AndroidInjection() 功能与 Dagger 2.16 进行集成测试呢?

最佳答案

我想出了以下方法将上下文注入(inject) dagger 2.11+ 的模块,所以这是一个开始,我仍然不知道如何从集成测试的角度处理应用程序。

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

这将使提供者可以使用上下文作为参数,并在其他人遇到这个特定问题时帮助他们。

关于android - 用于集成测试的 Dagger Inject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51517218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com