简体   繁体   中英

How do I insert test data in Play Framework 2.0 (Scala)?

I'm having some problems with making my tests insert fake data in my database. I've tried a few approaches, without luck. It seems that Global.onStart is not run when running tests within a FakeApplication, although I think I read that it should work.

object TestGlobal extends GlobalSettings {
  val config = Map("global" -> "controllers.TestGlobal")

  override def onStart(app: play.api.Application) = {
    // load the data ... 
  }
}

And in my test code:

private def fakeApp = FakeApplication(additionalConfiguration = (
  inMemoryDatabase().toSeq +
  TestGlobal.config.toSeq
).toMap, additionalPlugins = Seq("plugin.InsertTestDataPlugin"))

Then I use running(fakeApp) within each test.

The plugin.InsertTestDataPlugin was another attempt, but it didn't work without defining the plugin in conf/play.plugins -- and that is not wanted, as I only want this code in the test scope.

Should any of these work? Have anyone succeeded with similar options?

Global.onStart should be executed ONCE (and only once) when the application is launched, whatever mode (dev, prod, test) it is in. Try to follow the wiki on how to use Global .

In that method then you can check the DB status and populate. For example in Test if you use an in-memory db it should be empty so do something akin to:

if(User.findAll.isEmpty) {  //code taken from Play 2.0 samples

      Seq(
        User("guillaume@sample.com", "Guillaume Bort", "secret"),
        User("maxime@sample.com", "Maxime Dantec", "secret"),
        User("sadek@sample.com", "Sadek Drobi", "secret"),
        User("erwan@sample.com", "Erwan Loisant", "secret")
      ).foreach(User.create)   

  }

I chose to solve this in another way:

I made a fixture like this:

def runWithTestDatabase[T](block: => T) {
  val fakeApp = FakeApplication(additionalConfiguration = inMemoryDatabase())

  running(fakeApp) {
    ProjectRepositoryFake.insertTestDataIfEmpty()
    block
  }
}

And then, instead of running(FakeApplication()){ /* ... */} , I do this:

class StuffTest extends FunSpec with ShouldMatchers with CommonFixtures {
  describe("Stuff") {
    it("should be found in the database") {
      runWithTestDatabase {       // <--- *The interesting part of this example*
        findStuff("bar").size must be(1);
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM