【问题标题】:Dagger Inject for Integration Tests用于集成测试的 Dagger 注入
【发布时间】:2019-01-02 04:10:20
【问题描述】:

所以到 Dagger 2.11 之前,我已经能够构建 TestComponent 和 Modules 以使关键组件能够被注入到集成测试中。这对于 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 进行集成测试呢?

【问题讨论】:

    标签: android testing integration dagger


    【解决方案1】:

    我想出了以下方法将上下文注入到 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
        }
    }
    

    这将使上下文作为提供者的参数可用,并且应该在其他人到达这个特定的砖墙时帮助他们。

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 2021-10-16
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多