这是关于使用规格2的光滑3.1的播放2.4应用程序。 我在测试期间使用内存数据库和evolutions。我的问题是:目前,内存数据库在所有测试中保持活动状态,并且在每个测试用例后都不会重置为初始空状态。
我目前的代码如下:
package test
import play.api.test._
import play.api.test.Helpers._
import services.ProjectService
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import org.specs2.mutable._
import scala.concurrent.ExecutionContext.Implicits.global
import testhelpers.Injector
class ModelSpec extends Specification {
import models._
val projectService = Injector.inject[ProjectService]
"A project" should {
"be inserted" in {
running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {
val action = projectService.create("A")
.flatMap(_ => projectService.all)
val result = Await.result(action, Duration.Inf)
result must be_==(List(Project(1, "A")))
}
}
"be inserted2" in {
running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {
val action = projectService.create("A")
.flatMap(_ => projectService.all)
val result = Await.result(action, Duration.Inf)
result must be_==(List(Project(1, "A")))
}
}
}
}
首次测试通过。带错误的第二个测试失败:列表(项目(1,A),项目(2,A))不等于列表(项目(1,A))(ModelSpec.scala:42),因为保留了内存数据库在测试用例之间。
您可以在此处找到示例项目:https://github.com/nemoo/play-slick3-example
如何为每个测试用例创建一个新的数据库?
答案 0 :(得分:1)
这是implementation of imMemoryDatabase
:
def inMemoryDatabase(name: String = "default", options: Map[String, String] = Map.empty[String, String]): Map[String, String] = {
val optionsForDbUrl = options.map { case (k, v) => k + "=" + v }.mkString(";", ";", "")
Map(
("db." + name + ".driver") -> "org.h2.Driver",
("db." + name + ".url") -> ("jdbc:h2:mem:play-test-" + scala.util.Random.nextInt + optionsForDbUrl)
)
}
您可以看到它设置了db.whatever
个配置值,但Play Slick uses slick.dbs.whatever
,所以这对您没有帮助。以下是Play Slick使用的内容:
# Default database configuration
slick.dbs.default.driver="slick.driver.H2Driver$"
slick.dbs.default.db.driver="org.h2.Driver"
slick.dbs.default.db.url="jdbc:h2:mem:play"
您可能想要创建自己的inMemorySlickDatabase
(使用inMemoryDatabase
的实现作为灵感),设置相应的配置值。
答案 1 :(得分:0)
我创建了自己的def来设置光滑/ h2,这似乎工作正常。
即
def inMemoryDatabaseSlick(name: String = "default", options: Map[String, String] = Map.empty[String, String]): Map[String, String] = {
val optionsForDbUrl = options.map { case (k, v) => k + "=" + v }.mkString(";", ";", "")
Map(
("slick.dbs." + name + ".driver") -> "slick.driver.H2Driver$",
("slick.dbs." + name + ".db.driver") -> "org.h2.Driver",
("slick.dbs." + name + ".db.url") -> ("jdbc:h2:mem:play-test-" + scala.util.Random.nextInt + optionsForDbUrl)
)
}
然而我现在遇到的问题是我的H2数据库是空的,我看不到任何尝试将变换应用到它,填充它。我应该期待这个吗?或者我应该自己创建表格吗?