如何在Play Framework 2.0(Scala)中插入测试数据?

时间:2012-06-21 06:00:21

标签: unit-testing scala playframework playframework-2.0

我的测试在我的数据库中插入假数据时遇到了一些问题。我试过几种方法,没有运气。在FakeApplication中运行测试时似乎没有运行Global.onStart,尽管我认为我认为它应该可以工作。

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

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

在我的测试代码中:

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

然后我在每个测试中使用running(fakeApp)

plugin.InsertTestDataPlugin是另一次尝试,但如果没有在conf/play.plugins中定义插件就无法工作 - 这是不需要的,因为我只想在测试范围内使用此代码。

这些中的任何一个都有效吗?有没有人成功过类似的选择?

2 个答案:

答案 0 :(得分:1)

当应用程序启动时,无论运行何种模式(dev,prod,test),都应该执行ONCE(并且只执行一次)。尝试关注the wiki on how to use Global

在该方法中,您可以检查数据库状态并填充。例如,在Test中,如果你使用内存数据库,它应该是空的,所以做类似于:

的事情
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)   

  }

答案 1 :(得分:1)

我选择以另一种方式解决这个问题:

我做了这样的夹具:

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

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

然后,我执行此操作,而不是running(FakeApplication()){ /* ... */}

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);
      }
    }
  }
}
相关问题