【问题标题】:How to override dependency into real kodein app dependency graph?如何将依赖项覆盖到真正的kodein应用程序依赖图中?
【发布时间】:2018-02-15 13:55:11
【问题描述】:

我正在尝试进行一些测试,我需要通过在 KODEIN 上覆盖它来用假依赖替换真正的依赖,但它不起作用,我不知道我还能做什么。

这是我的依赖关系图(我省略了其他依赖关系):

class Injector(private val context: Context) {

    val dependencies = Kodein.lazy {

        .
        .
        bind<RetrieveContacts>() with provider {
            Log.i("RetrieveContacts","REAL")
            RetrieveContactsInMemory()
        }
        .
        .     
    }
}

这是我的应用程序类:

class AppApplication : Application(), KodeinAware {

   override val kodein by Injector(this).dependencies
}

这是我为覆盖依赖项所做的工作:

@RunWith(value = AndroidJUnit4::class)
class HomeActivityEmptyStateTest {

    @get:Rule
    var mActivityTestRule = ActivityTestRule<HomeActivity>(HomeActivity::class.java)

    @Before
    fun setup() {

        val appApplication = InstrumentationRegistry.getInstrumentation().targetContext

        val kodein by Kodein.lazy {

            extend(appApplication.appKodein())

            bind<RetrieveContacts>(overrides = true) with provider {
                Log.i("RetrieveContacts","FAKE")
                RetrieveEmptyContacts()
            }
        }
    }

    @Test
    fun testWhenHasNoContent() {
        ...
    }

}

我仍然在控制台日志中看到“RetrieveContacts REAL”而不是“RetrieveContacts FAKE”

【问题讨论】:

    标签: android dependency-injection kotlin kodein


    【解决方案1】:

    您在测试中扩展时似乎忘记允许覆盖。

    extend(appApplication.appKodein(), allowOverride = true)
    

    【讨论】:

      【解决方案2】:

      这不起作用,因为父定义不会被覆盖。更多信息:https://kodein.org/Kodein-DI/?6.1/core#_overridden_access_from_parent

      这是因为 Bar 绑定到单例,第一次访问会 定义使用的容器(父或子)。如果单例是 由孩子初始化,然后来自父母的后续访问将产生 一个引用了 Foo2 的 Bar,它不应该存在于 父母。

      【讨论】:

        猜你喜欢
        • 2014-03-18
        • 2015-11-21
        • 1970-01-01
        • 1970-01-01
        • 2020-04-12
        • 2021-03-02
        • 1970-01-01
        • 1970-01-01
        • 2014-07-21
        相关资源
        最近更新 更多