如何在 Kotlin 中将依赖项注入到接口委托中?

gro*_*wse 4 delegates dependency-injection composition kotlin

我试图弄清楚如何将依赖项注入到 Kotlin 中的接口委托中。我有一堂课:

class MyThingie {}
Run Code Online (Sandbox Code Playgroud)

我想created_time向此类添加一个字段,该字段也可能添加到其他类中。因此,我可以创建一个接口和该接口的实例实现,然后将该委托添加到类定义中:

interface ThingieWithCreatedTS {
    val created_ts: Long
}

object ThingieCreatedAtNow : ThingieWithCreatedTS {
    override val created_ts: Long = System.currentTimeMillis()
}

class MyThingie : ThingieWithCreatedTS by ThingieCreatedAtNow {}
Run Code Online (Sandbox Code Playgroud)

这很棒。现在我可以调用created_ts任何实例MyThingie并获取它创建的时间戳。然而,现在这很难测试。

我真的不想尝试模拟System,并且我理解正确的模式是将某种 Clock 实例注入任何需要知道当前时间的对象中。这样,我可以在代码中提供一个 RealClock,并且在测试中我可以提供一个 FakeClock(我可以控制其输出)。

目前尚不清楚我如何在这种模式上做到这一点。如何将实现实例传递给委托?

IR4*_*R42 8

为什么不直接使用构造函数依赖注入呢?

class MyThingie(
    dep: ThingieWithCreatedTS = ThingieCreatedAtNow
) : ThingieWithCreatedTS by dep {}
Run Code Online (Sandbox Code Playgroud)

现在您可以ThingieWithCreatedTS在测试中提供虚假依赖项

  • 在处理 Activity 时如何实现相同的目标?我们无法构造函数注入活动。 (2认同)