PlayFramework Scala Test - Get instance of a class via dependency injector

1k views Asked by At

I am using Scala Test for testing my service layer. I am struggling to getinstance of service class in my test. My test class is as below

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
    }
  }
 }
}

Edited Code, as per @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
  }
}
}

}

I am not sure how to get instance of SMS service in the above code.

Thanks,

1

There are 1 answers

0
Luong Ba Linh On

You can use Guice for dependency injection. It is a good practice to abstract services at compilation time and specify a binding between services abstractions and their implementations at run time.

For example,

class SmsServiceImpl extends SmsService

bind(classOf[SmsService]).to(classOf[SmsServiceImpl])

This, https://github.com/luongbalinh/play-mongo, is a simple but standard application using Play 2.4.2, ReactiveMongo, and Guice (for dependency injection).