PlayFramework Scala测试-通过依赖项注入器获取类的实例
我正在使用Scala测试来测试我的服务层。在测试中,我正在努力获取服务类的实例。我的测试课程如下PlayFramework Scala测试-通过依赖项注入器获取类的实例,scala,playframework,scalatest,playframework-2.4,Scala,Playframework,Scalatest,Playframework 2.4,我正在使用Scala测试来测试我的服务层。在测试中,我正在努力获取服务类的实例。我的测试课程如下 class SmsServiceSpec extends BaseSpec with OneAppPerSuite with ScalaFutures { implicit override lazy val app: FakeApplication = FakeApplication() "SMS Service" must { "able to send SMS" in {
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 绑定(classOf[SmsService])到(classOf[SmsServiceImpl])
这是一个简单但标准的应用程序,使用Play2.4.2、ReactiveMongo和Guice(用于依赖项注入).所以我对2.4不太熟悉,我知道DI改变了一些东西,但在我的应用程序中,我使用2.3 w/Guice,对于我设置中的单元测试,我自己实例化类并传递依赖项或模拟等。你能做类似的事情吗?你注释掉的那行有什么问题。在重头戏2.4中,只要SmsService用@Inject注释或有一个0参数构造函数,它就应该“正常工作”。@barry-这个特殊的测试不能用于模拟。我想测试我是否真的在手机上收到短信:(@easel-我更新了上面的代码,但我的属性仍然为null。我想你还有其他问题。可能是缺少库、配置或重写的全局模块。我有一个类似于以下的特性,为了方便引用服务等,我混合到测试中,它“只起作用”。特性注入{def app:Application=app.injector def actorSystem:actorSystem=injector.instanceOf[actorSystem]