0

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 Answers2

2

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.

bjfletcher
  • 11,168
  • 4
  • 52
  • 67
  • Thank you @bjfletcher for your prompt answer! If I mock the reactiveMongoApi however, I will not be able to interact with a local MongoDB instance? Is there any other alternative then? Thank you! –  Jul 07 '15 at 20:42
  • 1
    Unit testing with a real database - you're dangerous in my book. :) – bjfletcher Jul 07 '15 at 21:24
  • Thank you for your answer. Yes, you are right this is not a good solution. This is due to the fact that it is not possible to embed a MongoDB instance for unit tests (the existing solutions are not maintained, etc.). –  Jul 08 '15 at 20:23
0

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

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

Luong Ba Linh
  • 802
  • 5
  • 20