简体   繁体   中英

Scala Play 2.4: How to pass MessagesApi explicitly?

I created a small CRUD application to learn more about Scala and Play. Following the CRUD template, I obtained the solution posted here on GitHub . I have been struggling to develop effective tests for this using Specs2. Now I would like to test the controller. It has this signature:

class PersonController @Inject() (repo: PersonRepository, val messagesApi: MessagesApi)
                         (implicit ec: ExecutionContext) extends Controller with I18nSupport

To test an action of the controller, I should create a new controller. While I see how I can mock away the repository and the WithApplication trait will provide the ExecutionContext, I don't see how to deal with the MessagesApi.

1) Shall I create an instance of it or retrieve it from somewhere and pass explicitly? how?

2) Shall I mock it too? how?

Thank you for your help.

For unit tests, I would go with a mock. Both specs2 ( docs ) and ScalaTest ( docs ) have some level of integration with Mockito.

For functional tests, I would go with using WithApplication scope (in the case of specs2) and using the app injector to create the controller instance:

"should test using an injected controller" in new WithApplication {
  val applicationController = app.injector.instanceOf[controllers.Application]
  val result: Future[mvc.Result] = applicationController.index()(FakeRequest())

  status(result) must equalTo(OK)
}

This way, Play injector will create your controller instance with all the necessary dependencies, including MessageApi .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM