我使用Play-slick进行Slick集成,使用Guice注入DAO。创建表格和填充种子数据的演变,即1.sql, 2.sql, ...
。我差不多完成了,我想将Evolutions文件和application.conf
分成两个环境。
我创建了两组conf/application.conf
和test/conf/application.test.conf
指向不同的数据库进行测试和实时部署。我已将build.sb设置为application.test.conf
用于test
,
javaOptions in Test += "-Dconfig.file=test/conf/application.test.conf"
application.test.conf
内容,
slick.dbs.h2test.driver = "slick.driver.H2Driver$"
slick.dbs.h2test.db.driver = org.h2.Driver
slick.dbs.h2test.db.url = "jdbc:test.h2:mem:play;MODE=MYSQL;DB_CLOSE_DELAY=-1"
如何配置我的测试用例/套件以使用h2test
上下文(即conf/evolutions/h2test/1.sql
)代替default
来填充测试数据并再次运行Slick查询h2test
?我尝试使用FakeApplication
和GuiceApplicationBuilder
方式取得了有限的成功。感谢
答案 0 :(得分:5)
class EmployeeRepositorySpec extends PlaySpecification{
import models._
"Employee repository" should {
def empRepo(implicit app: Application) = Application.instanceCache[EmployeeRepository].apply(app)
"get all rows" in new WithApplication() {
val result = await(empRepo.getAll)
result.length === 4
result.head.name === "sky"
}
"get single rows" in new WithApplication() {
val result = await(empRepo.getById(1))
result.isDefined === true
result.get.name === "Vikas"
}
"insert a row" in new WithApplication() {
val knolId = await(empRepo.insert(Employee("sky", "sky@knoldus.com", "knoldus","Senior Consultant")))
knolId === 5
}
"insert multiple rows" in new WithApplication() {
val result = empRepo.insertAll(List(Employee("sky1", "sky1@knoldus.com", "knoldus","Senior Consultant"),
Employee("sky2", "sky2@knoldus.com", "knoldus","Senior Consultant")))
val knolIds = await(result)
knolIds === Seq(5, 6)
}
"update a row" in new WithApplication() {
val result = await(empRepo.update(Employee("sky", "sky@knoldus.com", "knoldus","Senior Consultant", Some(1))))
result === 1
}
"delete a row" in new WithApplication() {
val result = await(empRepo.delete(1))
result === 1
}
}
def await[T](v: Future[T]): T = Await.result(v, Duration.Inf)
}
答案 1 :(得分:1)
我添加了play.slick.db.default = test
来覆盖application.test.conf
中的默认。最重要的是,我添加了
play.evolutions.db.default.autoApply = false
slick.dbs.default.driver = "slick.driver.H2Driver$"
slick.dbs.default.db.driver = "org.h2.Driver"
slick.dbs.default.db.url = "jdbc:h2:mem:nothing"
否则,Evolution还会填充由"默认"定义的其他数据库。和我的"其他数据库"由于连接到不存在的数据库失败,导致我的测试失败。
答案 2 :(得分:0)
您可以创建一个通用类,为所有存储库编写测试用例,如下所示:
class TestModel[T: ClassTag] extends WithApplicationLoader {
lazy val app2dao = Application.instanceCache[T]
lazy val repository: T = app2dao(app)
def result[R](response: Future[R]): R =
Await.result(response, 2.seconds)
}
现在,在TestModel中传递Test Class,从而在测试用例中创建一个对象,如下所示:
class TestRepositoryTest extends Specification {
private val modelTest = new ModelsTest[TestRepository]
"Test Repository" should {
"store a user" in {
val testObj = Test(0, "test@example.com", new DateTime(System.currentTimeMillis))
val storeResult =
modelTest.result(modelTest.repository.store(testObj))
storeResult must equalTo(1)
}
}
}