Testing Scala application using Play framework and Mockito
12 July 2017
In this example the controller class Product Controller fetches data from an external service called DataService. Since we can't call real APIs during Test we need to mock DataService and return mock data instead. Similar to Java, in Scala there are also many options for using mock libraries. One popular mock library is Mockito, in this example we use it to return a fake instance and inject it into the application in test using GuiceApplicationBuilder, we also leverage play framework's testing support capability. The test reads from a JSON file Source called "sample_offer_list.json", builds the json object representation and validates the fields values.
Injected JSON Mock data
Sample Test
@RunWith(classOf[JUnitRunner])classProductControllerSpecextendsPlaySpecwithMockitoSugar{/ MOCK data /valproductList=Json.parse(Source.fromFile("conf/app/sample_offer.json").getLines.mkString).as[OfferList] valmyMock=mock[DataRepository]when(myMock.search(any[Map[String,String]]))thenReturnFuture.successful(Some(productList)) valappMock=newGuiceApplicationBuilder().overrides(bind[DataRepository].toInstance(myMock)).build"index"innewWithApplication(appMock){valrequest=FakeRequest(GET,"/products").withHeaders(HOST->"localhost:9000")valresponse=route(app,request).getvaljson=contentAsJson(response)valelem0=(json\"list")(0)status(response)mustBeOK(elem0\"id").as[String]mustBe"1"(elem0\"name").as[String]mustBe"prod 1"}}