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

时间:2019-05-21 17:20:01

标签: scala mockito scalatest companion-object

我有一个这样的Scala类:

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注入伴随对象字段,那将是很好的。还是我想念其他东西?

1 个答案:

答案 0 :(得分:3)

为什么不只是进行依赖注入

例如

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"