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.
@Singleton
class ExampleCtrl @Inject() (dao: TestDAO) extends Controller {
//code here
def testMethod = Action { request =>
dao.exampleMethod()
Ok(Json.obj("test" -> "test")
}
}
class TestDAO @Inject()(protected val provider: DatabaseConfigProvider){
def exampleMethod()
}
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"}]"""
}
}
}
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)