繁体   English   中英

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

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

我在使测试在数据库中插入伪数据时遇到一些问题。 我尝试了几种方法,但是没有运气。 在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定义插件,该插件将无法工作-并不需要,因为我只想在测试范围中使用此代码。

这些应该工作吗? 有没有人成功获得类似的选择?

无论应用程序处于哪种模式(dev,prod,test),启动应用程序时,Global.onStart应该一次执行(并且仅执行一次)。尝试按照Wiki上的方法使用Global

然后,可以使用该方法检查数据库状态并进行填充。 例如,在“测试”中,如果您使用内存数据库,则该数据库应为空,因此请执行以下操作:

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)   

  }

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

我做了一个这样的装置:

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);
      }
    }
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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