Search code examples
scalaplayframeworkmockitoguicescalatest

Inject dependency of mock service object in play controller while unit testing it


I have a controller which looks like

class MyController @Inject()(service: MyService,
                                 cc: MessagesControllerComponents
                     )(implicit ec: ExecutionContext)
  extends MessagesAbstractController(cc) {

def getAll ....// all methods of controller

Now, I am trying to unit test the controller using Mockito and Scalatest where I am trying to inject the mocked object of MyService in unit test. My unit test is as follows

class MyControllerTest extends PlaySpec with GuiceOneAppPerSuite {

  "MyController" should {

    def fakeApplication(): Application = new GuiceApplicationBuilder().build()

    "not return 404" when {
      "we try to hit the route /ads" in {
        val fakeRequest = FakeRequest(GET, "/ads")
        val futureResult: Future[Result] = route(fakeApplication, fakeRequest).get
        val resultJson: JsValue = contentAsJson(futureResult)(Timeout(2, TimeUnit.SECONDS))
        resultJson.toString mustBe """{"status":"success"}"""
      }
    }
  }
}

Now to unit test the controller, I need to pass in the mock of the service in the controller while building it via guice. I tried the following method to inject the mocked dependency in controller,

val application = new GuiceApplicationBuilder()
  .overrides(bind[MyService])
  .build

However, it fails to inject the mocked service object. Any pointers on where I am going wrong will be highly appreciated. Thanks in advance.


Solution

  • You have to do something like

    val application = new GuiceApplicationBuilder()
      .overrides(bind[MyService].toInstance(yourMock))
      .build