将模拟对象注入伴随对象字段

Inject mock object to companion object field

我有一个像这样的 Scala class:

object MyClient {
  private lazy val theClient: TheClient = new TheClient()
}

class MyClient {
  import MyClient._

  var client = null // this is only for unittest

  def getSomethingFromTheClient() = {
    if (client == null) client = theClient 
    client.getSomething() + " from MyClient" 
  }
}

有些代码只是为了方便单元测试,我可以在其中模拟 TheClient 并将其注入 MyClient,就像这样(我正在使用 Mockito):

val mockTheClient = mock[TheClient]
val testMyClient = new MyClient()
testMyClient.client = mockTheClient
testMyClient.getSomethingFromTheClient() shouldBe "blabla"

这有效但看起来很丑。理想情况下,如果我可以将 mockTheClient 注入到伴随对象字段中,那就太好了。还是我错过了其他东西?

你为什么不直接做依赖注入

例如

lazy val client: TheClient = new TheClient()

class MyClient(client: => TheClient) {
  def getSomethingFromTheClient() = {
    client.getSomething() + " from MyClient" 
  }
}

然后在测试中

val mockTheClient = mock[TheClient]
val testMyClient = new MyClient(mockTheClient)
testMyClient.getSomethingFromTheClient() shouldBe "blabla"