【问题标题】:How to inject mocks with Dagger 2.11如何使用 Dagger 2.11 注入模拟
【发布时间】:2017-08-04 22:49:51
【问题描述】:

我正在尝试使用 Dagger 2.11 的 Android Injector 注入模拟。

在使用 Android Inject 之前,我曾经更改 Application 类中的注入器,以便可以注入模拟。像这样:

class EGOApplication : Application() {

    lateinit var injectorComponent: InjectorComponent


    override fun onCreate() {
        super.onCreate()

        injectorComponent = DaggerInjectorComponent.builder()
                .appModule(AppModule(this))               
                .build()
}

在我的测试中,我曾经像这样更改注入器组件:

app.injectorComponent = DaggerMockComponent.builder()
                .mockModule(MockModule(app))
                .build()

然后我可以从 MockModule 注入我的模拟。

但现在我在本教程中使用 Android Injector:https://medium.com/@iammert/new-android-injector-with-dagger-2-part-1-8baa60152abe

嗯...现在我像这样注入我的依赖项:

override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
}

所以我的方法不再适用了... 如何从我的 MockModule 中创建 Dagger 注入器依赖项?

感谢任何帮助!

【问题讨论】:

  • 嘿,我也有同样的问题。你找到什么方法了吗?
  • 是的,我做到了。检查我的答案。

标签: android dependency-injection kotlin dagger-2 dagger


【解决方案1】:

我找到了答案。

我在测试中更改了 injectorComponent... 像这样:

@Inject
lateinit var someDependency: SomeDependency

val app = instrumentation.targetContext.applicationContext as MyApplication

app.injectorComponent = DaggerMockComponent.builder()
                .mockModule(MockModule(app))
                .build()

if (null == mockComponent) {
      mockComponent = app.injectorComponent as MockComponent
      mockComponent!!.inject(this)
}

我的申请或多或少是这样的:

open class MyApplication : Application(), HasActivityInjector {
        @Inject
        lateinit var androidInjector : DispatchingAndroidInjector<Activity>

    lateinit var injectorComponent: InjectorComponent

    override fun onCreate() {
        super.onCreate()              

        buildInjector()

    }


    open fun buildInjector() {
        injectorComponent = DaggerInjectorComponent.builder()
                .dataModule(DataModule())
                .appModule(AppModule(this))
                .trackerModule(TrackerModule(this, FirebaseAnalytics.getInstance(this)))
                .build()
    }

    override fun activityInjector(): AndroidInjector<Activity> = androidInjector

}

但是现在我在我的测试中使用不同的应用程序,我扩展了默认应用程序(一个 TestApplication)。在这个应用程序中,我构建了一个不同的注入器:

class TestApplication : MyApplication() {

    override fun buildInjector() {
        injectorComponent = DaggerMockComponent.builder().mockModule(MockModule(this)).build()
    }
}

您将需要创建一个扩展 InjectorComponent 的 MockComponent 和一个提供您需要的所有模拟的 MockModule。

然后在你的测试中做:

@Before
fun setUp() {
    val app = instrumentation.targetContext.applicationContext as TestApplication
    (app.injectorComponent as MockComponent).inject(this)
}

它工作得很好!

【讨论】:

    猜你喜欢
    • 2019-01-06
    • 2022-01-11
    • 2017-10-07
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多