mardi 29 mars 2016

Play Framework and Slick: testing database-related services

I'm trying to follow the most idiomatic way to having a few fully tested DAO services.

I've got a few case classes such as the following:

case class Person (
  id        :Int,
  firstName :String,
  lastName  :String
)

case class Car (
  id      :Int,
  brand   :String,
  model   :String
)

Then I've got a simple DAO class like this:

class ADao @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends HasDatabaseConfigProvider[JdbcProfile] {
  import driver.api._

  private val persons = TableQuery[PersonTable]
  private val cars = TableQuery[CarTable]
  private val personCar = TableQuery[PersonCar]

  class PersonTable(tag: Tag) extends Table[Person](tag, "person") {
    def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
    def firstName = column[String]("name")
    def lastName = column[String]("description")
    def * = (id, firstName, lastName) <> (Person.tupled, Person.unapply)
  }

  class CarTable(tag: Tag) extends Table[Car](tag, "car") {
    def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
    def brand = column[String]("brand")
    def model = column[String]("model")
    def * = (id, brand, model) <> (Car.tupled, Car.unapply)
  }

  // relationship
  class PersonCar(tag: Tag) extends Table[(Int, Int)](tag, "person_car") {
    def carId = column[Int]("c_id")
    def personId = column[Int]("p_id")
    def * = (carId, personId)
  }

  // simple function that I want to test
  def getAll(): Future[Seq[((Person, (Int, Int)), Car)]] = db.run(
    persons
      .join(personCar).on(_.id === _.personId)
      .join(cars).on(_._2.carId === _.id)
      .result
  )  
}

And my application.conf looks like:

slick.dbs.default.driver="slick.driver.PostgresDriver$"
slick.dbs.default.db.driver="org.postgresql.Driver"
slick.dbs.default.db.url="jdbc:postgresql://super-secrete-prod-host/my-awesome-db"
slick.dbs.default.db.user="myself"
slick.dbs.default.db.password="yolo"

Now by going through Testing with databases and trying to mimic play-slick sample project I'm getting into so much trouble and I cannot seem to understand how to make my test use a different database (I suppose I need to add a different db on my conf file, say slick.dbs.test) but then I couldn't find out how to inject that inside the test.

Also, on the sample repo, there's some "magic" like Application.instanceCache[CatDAO] or app2dao(app).

Can anybody point me at some full fledged example of or repo that deals correctly with testing play and slick?

Thanks.

Aucun commentaire:

Enregistrer un commentaire