0
votes

In the following, I am using the Play2 ReactiveMongo plugin in version 0.11.0.play24 (https://github.com/ReactiveMongo/Play-ReactiveMongo) for Play 2.4.

As mentioned in the documentation located at http://reactivemongo.org/releases/0.11/documentation/tutorial/play2.html, a Play2 controller with Mongo is instantiated as follows:

class MyController @Inject() (val reactiveMongoApi: ReactiveMongoApi)
extends Controller with MongoController with ReactiveMongoComponents { }

Therefore, since the controller is now a class and not an object, it is not possible to use it as a singleton in the test cases.

However, I do not know how to inject the reactiveMongoApi in order to instantiate a MyController() with the right parameters in a test case (ScalaCheck or other...)

Do you have any idea/example on how to test such a controller with ScalaCheck or Specs2?

Thank you in advance!

2

2 Answers

2
votes

You can produce a mock for ReactiveMongoApi (depending which mock framework you use):

val reactiveMongoApi = mock[ReactiveMongoApi]

and then you can do this:

new MyController(reactiveMongoApi)

That's the simplest approach. To use the actual ReactiveMongoApi object:

val app = new GuiceApplicationBuilder()
  .in(Mode.Test)
  .configure("play.modules.enabled" -> "play.modules.reactivemongo.ReactiveMongoModule")
  .build

val reactiveMongoApi = app.injector.instanceOf[ReactiveMongoApi]

If it gets more complicated, for example, partially mocked nested dependency tree (this is more integration testing than unit testing), you may want to partially mock the Guice framework as explained here.

0
votes

This project use Guice for dependency injection, Spec2 for testing controllers, and Frisby for testing endpoints.

https://github.com/luongbalinh/play-mongo