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



我有一个类似的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" 
  }
}

某些代码仅在那里促进Untistest,我可以在这里模拟theclient并将其注入myclient,例如这样(我正在使用Mockito(:

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

这起作用,但似乎很丑。理想情况下,如果我可以向伴随对象字段注入模仿,那将是很棒的。还是我想念其他东西?

为什么不做依赖注入

例如

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"

相关内容

  • 没有找到相关文章

最新更新