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

谢谢,

4

1 回答 1

0

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

例如,

类 SmsServiceImpl 扩展了 SmsService

绑定(classOf[SmsService]).to(classOf[SmsServiceImpl])

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

于 2015-07-30T16:05:31.473 回答