我正在使用Scala测试来测试我的服务层。我在考试中努力争取获得服务等级的实例。我的测试课如下

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服务实例。

谢谢,

最佳答案

您可以使用Guice进行依赖项注入。优良作法是在编译时抽象服务,并在运行时在服务抽象及其实现之间指定绑定。
例如,

SmsServiceImpl类扩展SmsService
bind(classOf [SmsService])。to(classOf [SmsServiceImpl])

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

10-07 22:48