Reputation: 8281
How to pass a service to a controller with Playframework 2.4
I've tried to pass the service in the constructor (simple solution)
class Application(val service: Service) extends Controller {…}
But how to write a functional test with specs2, and more precisely how can I instantiate a controller with a fake service :
"…" in new WithApplication {…}
Here is the error
[error] 1) Could not find a suitable constructor in controllers.Application. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
Upvotes: 0
Views: 149
Reputation: 331
I'm learning, like you, this aspect of the Framework. I understood that you can create of Mock of your service, using Mockito (default mocking library in the framework) and instantiate your controller with it. Something like that:
import org.specs2.mock._
class ApplicationTestSpec extends Specification with Mockito {
lazy val mockService = mock[Service]
// Details of the mock object need to be added.
"..." in new WithApplication {
val mockedController = new controllers.Application(mockRepo)
...
}
}
The documentation of Mockito should tell you how to precisely mock your service. I hope it helps.
Edit: indeed, this would work for unit test, not functional one. My bad.
Upvotes: 0
Reputation: 186
I would inject the service in the controller:
import javax.inject._
class Application @Inject (val service: Service) extends Controller {…}
Then bind the service to different implementations based on different configs for dev and tests.
Upvotes: 1