PlayFramework Scala测试 - 通过依赖注入器获取类的实例

时间:2015-06-23 13:58:09

标签: scala playframework scalatest playframework-2.4

我正在使用Scala Test来测试我的服务层。我正努力在我的测试中获得服务类的实例。我的测试类如下

class SmsServiceSpec extends BaseSpec with OneAppPerSuite with ScalaFutures {

implicit override lazy val app: FakeApplication = FakeApplication()

"SMS Service" must {
   "able to send SMS" in {

    val smsService =  //not sure how to get instance of class here => app.injector.getInstance[SmsService]

    whenReady(smsService.sendSms("9XXXXXXX", "This is test message")) { res =>
      res mustBe true
    }
  }
 }
}

编辑代码,根据@easel

class SmsServiceSpec extends BaseSpec with OneAppPerSuite with ScalaFutures {

 "SMS Service" must {
"able to send SMS" in {

  @Inject val smsService: SmsService = null //not sure how to get instance of class here => app.injector.getInstance[SmsService]

  whenReady(smsService.sendSms("98XXXXXX", "This is test message")) { res =>
    res mustBe true
  }
}
}

}

我不确定如何在上面的代码中获取SMS服务的实例。

谢谢,

1 个答案:

答案 0 :(得分:0)

您可以使用Guice进行依赖注入。在编译时抽象服务并在运行时指定服务抽象与其实现之间的绑定是一种很好的做法。

例如,

  

类SmsServiceImpl扩展了SmsService

     

绑定(classOf [SmsService])。到(classOf [SmsServiceImpl])

这个https://github.com/luongbalinh/play-mongo是一个简单但标准的应用程序,使用Play 2.4.2,ReactiveMongo和Guice(用于依赖注入)。