Search code examples
scalaplayframeworkspecs2playframework-2.4

Scala Play2 router/controller test without hitting database


I have a simple controller test that goes through the router:

 "returns all reservations" should {
    running(FakeApplication()) {
      val Some(result) = route(FakeRequest(GET, "/reservations?envId=560d89ec5393af5d00bcfdf1"))

      mustBeValidResponse(result)
      contentAsString(result) must contain("environmentId")
    }
  }

But as you can see, it requires an ID as part of the URL, meaning my test is dependent on data that is in the database, which is no good. How do I create a fixture or something that the test will run against so the test runs without actually relying on data in the database?


Solution

  • I assume that the code accessing the database is not directly in the controller, but in another class which is injected to the controller. You should use module system indroduced in Play version 2.4. Then what you need is to replace the real implementation which accesses DB by a mock. More info here: https://www.playframework.com/documentation/2.4.x/ScalaTestingWithGuice#Overriding-bindings-in-a-functional-test