Fixtures in Play! 2 for Scala

走远了吗. 提交于 2019-12-03 03:25:27

Use Evolutions. Write a setup and teardown script for the fixtures in SQL, or use mysqldump (or equivalent for your DB) to export an existing test DB as sql.

http://www.playframework.org/documentation/1.2/evolutions

I find the most stress-free way to do testing is to set everything up in an in-memory database which means tests run fast and drive the tests from Java using JUnit. I use H2DB, but there are a few gotchas you need to watch out for. I learned these the hard way, so this should save you some time.

Play has a nice system for setting up and tearing down your application for integration testing, using running( FakeAplication() ) { .. }, and you can configure it to use an in memory database with FakeApplication(additionalConfiguration = inMemoryDatabase()) see:

http://www.playframework.org/documentation/2.0/ScalaTest

OutOfMemory errors: However, running a sizeable test fixture a few times on my machine caused OutOfMemory errors. This seems to be because the default implementation of the inMemoryDatabase() function creates a new randomly named database and doesn't clean up the old ones between test runs. This isn't necessary if you've written your evolution teardown scripts correctly, because the database will be emptied out and refilled between each test. So we overrode this behaviour to use the same database and the memory issues disappeared.

DB Dialect: Another issue is that our production database is MySQL which has a number of incompatibilities with H2DB. H2DB has compatibility modes for a number of dbs, which should reduce the number of problems you have:

http://www.h2database.com/html/features.html#compatibility

Putting this all together makes it a little unwieldy to add before each test, so I extracted it into a function:

def memDB[T](code: =>T) = 
  running( FakeApplication( additionalConfiguration = Map( 
    "db.default.driver" -> "org.h2.Driver", 
    "db.default.url"    -> "jdbc:h2:mem:test;MODE=MySQL" 
  ) ) )(code) 

You can then use it like so (specs example):

"My app" should {
  "integrate nicely" in memDB {
    .....
  }
}

Every test will start a fake application, run your fixture setup evolutions script, run the test, then tear it all down again. Good luck!

Why not use the java example in Scala? That exact code should also work without modifications in Scala...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!