Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Let's create a simple Unit Test for Play Framework project!
- // BuildingDao.scala (taken from https://pastebin.com/yNiBWTpf)
- package dao
- import javax.inject.Inject
- import scala.concurrent.Future
- import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
- import play.db.NamedDatabase
- import slick.jdbc.JdbcProfile
- import slick.lifted.ProvenShape
- case class Building(buildingId: Option[Long], number: Option[Int], name: String)
- class BuildingDao @Inject()(
- @NamedDatabase("students") val dbConfigProvider: DatabaseConfigProvider
- ) extends HasDatabaseConfigProvider[JdbcProfile] {
- import profile.api._
- private class BuildingTable(tag: Tag) extends Table[Building](tag, "building") {
- def buildingId: Rep[Long] = column[Long]("building_id", O.PrimaryKey, O.AutoInc)
- def number: Rep[Option[Int]] = column[Option[Int]]("number")
- def name: Rep[String] = column[String]("name")
- override def * : ProvenShape[Building] = (buildingId.?, number, name) <> (Building.tupled, Building.unapply)
- }
- private lazy val table = TableQuery[BuildingTable]
- def findByNumber(number: Int): Future[Option[Building]] = {
- val query = table.filter(_.number === number).result
- println(query.statements.mkString)
- db.run(query.headOption)
- }
- }
- // CampusController.scala
- package controllers
- import javax.inject.Inject
- import scala.concurrent.ExecutionContext
- import play.api.libs.json.Json
- import play.api.mvc._
- import dao.BuildingDao
- /**
- * CampusController
- * @param cc Controller Components
- */
- class CampusController @Inject()(
- buildingDao: BuildingDao,
- cc: ControllerComponents
- )(implicit val ec: ExecutionContext) extends AbstractController(cc) {
- def health: Action[AnyContent] = Action {
- Ok("Service is OK")
- }
- def getBuildingByNumber(num: Int): Action[AnyContent] = Action.async {
- buildingDao.findByNumber(num) map {
- case Some(bld) => Ok(Json.toJson("id" -> bld.buildingId, "name" -> bld.name, "number" -> bld.number))
- case None => NotFound(s"Building with num = $num not found")
- }
- }
- }
- // and finally the Unit Test itself
- // CampusControllerSpec.scala
- import controllers.CampusController
- import scala.concurrent.Future
- import org.mockito.Mockito._
- import org.scalatest.BeforeAndAfterEach
- import org.scalatest.mockito.MockitoSugar
- import org.scalatestplus.play.PlaySpec
- import play.api.libs.json.Json
- import play.api.test.FakeRequest
- import play.api.test.Helpers._
- import play.mvc.Http.MimeTypes
- import dao.{Building, BuildingDao}
- /**
- * Unit test for CampusController. Just extend "PlaySpec" class
- */
- class CampusControllerSpec extends PlaySpec with MockitoSugar with BeforeAndAfterEach {
- // some common constants
- val buildingId = 127
- val buildingName = "Mathematics"
- // since resetting stubs is considered to be bad practice, we will re-create the stubs before each test
- var buildingDao: BuildingDao = _
- var controller: CampusController = _
- // "beforeEach()" will be executed before each test; just mix-in "BeforeAndAfterEach" trait to override it
- override protected def beforeEach(): Unit = {
- // let's mock BuildingDao's behaviour: we suppose that Building #5 exists, and Building #6 doesn't
- buildingDao = mock[BuildingDao] // mix-in "MockitoSugar" trait for this
- when (buildingDao.findByNumber(5)) thenReturn Future.successful(Some(Building(Some(buildingId), Some(5), buildingName)))
- when (buildingDao.findByNumber(6)) thenReturn Future.successful(None)
- // also we will use predefined ControllerComponents for our controller
- val cc = stubControllerComponents()
- implicit val ec = cc.executionContext
- // create our Controller for testing
- controller = new CampusController(buildingDao, cc)
- }
- "CampusController" when {
- "empty request received" should {
- "return OK 200" in {
- val result = controller.health.apply(FakeRequest()) // basic test
- status(result) mustBe OK
- contentAsString(result) mustBe "Service is OK"
- contentAsString(result) must include("is")
- contentAsString(result) must startWith("Service")
- contentAsString(result) must endWith("OK")
- }
- }
- "request for an existing building received" should {
- "return OK 200" in {
- val number = 5
- val expectedJson = Json.toJson("id" -> buildingId, "name" -> buildingName, "number" -> number)
- val result = controller.getBuildingByNumber(number).apply(FakeRequest()) // will return info about Building #5
- status(result) mustBe OK
- contentType(result) mustBe Some(MimeTypes.JSON)
- contentAsJson(result) mustBe expectedJson
- }
- }
- "request for a non-existing building received" should {
- "return NOT_FOUND 404" in {
- val number = 6
- val result = controller.getBuildingByNumber(number).apply(FakeRequest()) // will return "Building #6 not found"
- status(result) mustBe NOT_FOUND
- contentAsString(result) mustBe s"Building with num = $number not found"
- }
- }
- }
- }
- // sbt testOnly *CampusControllerSpec
- // output:
- // [info] CampusControllerSpec:
- // [info] CampusController
- // [info] when empty request received
- // [info] - should return OK 200
- // [info] when request for an existing building received
- // [info] - should return OK 200
- // [info] when request for a non-existing building received
- // [info] - should return NOT_FOUND 404
- // [info] ScalaTest
- // [info] Run completed in 2 seconds, 820 milliseconds.
- // [info] Total number of tests run: 3
- // [info] Suites: completed 1, aborted 0
- // [info] Tests: succeeded 3, failed 0, canceled 0, ignored 0, pending 0
- // [info] All tests passed.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement