Search code examples
scalaplayframework-2.0scalatest

Play/Scala injecting Object into controller for testing


I saw this thread Play/Scala injecting controller into test I have similar issue like this, but my issue is how to inject the object for testing the controller.

Controller

@Singleton
class ExampleCtrl @Inject() (dao: TestDAO) extends Controller {
//code here
   def testMethod = Action { request =>
       dao.exampleMethod()
       Ok(Json.obj("test" -> "test")
   }
 }

DAO

class TestDAO @Inject()(protected val provider: DatabaseConfigProvider){
  def exampleMethod()
}

Test

class ExampleCtrlSpec extends PlaySpec with MockitoSugar {
  val service = mock[TestDAO]//problem on injecting DatabaseConfigProvider
  val controller = new ExampleCtrl(service)
  //service has null value for DatabaseConfigProvider properties

  "testMethod()" should {
    "return JSON" in {
      when(service.exampleMethod) thenReturn "json data"
      val result: Future[Result] =
      controller.testMethod().apply(FakeRequest())
      .withJsonBody(JSON.json("""[{"test":"test"}]"""))
      contentAsString(result) mustEqual """[{"test":"test"}]"""
    }
  }
}

Solution

  • I solved the problem on the following way.

    def testDAO (implicit app: Application) = {
        val app2testDAO = Application.instanceCache[TestDAO ]
        app2testDAO(app)
    }
    val controller = new ExampleCtrl(testDAO)