Scala 如何在Play framework和slick的单元测试中删除创建会话的代码
我正在使用Play2.0和slick。所以我为这样的模型编写单元测试Scala 如何在Play framework和slick的单元测试中删除创建会话的代码,scala,playframework,playframework-2.1,slick,Scala,Playframework,Playframework 2.1,Slick,我正在使用Play2.0和slick。所以我为这样的模型编写单元测试 describe("add") { it("questions be save") { Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession { // given Questions.ddl.create Questions.add(questionFixture) //
describe("add") {
it("questions be save") {
Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession {
// given
Questions.ddl.create
Questions.add(questionFixture)
// when
val q = Questions.findById(1)
// then
// assert!!!
}
}
}
before {
Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession {
Questions.ddl.create
}
}
describe("add") {
it("questions be save") {
// given
Questions.add(questionFixture)
// when
val q = Questions.findById(1)
// then
// assert!!!
}
}
}
它工作得很好,但是下面的代码片段在每个单元测试中都会被复制
Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession {
Questions.ddl.create
// test code
}
所以,我想把代码移到before块,类似这样的东西
describe("add") {
it("questions be save") {
Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession {
// given
Questions.ddl.create
Questions.add(questionFixture)
// when
val q = Questions.findById(1)
// then
// assert!!!
}
}
}
before {
Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession {
Questions.ddl.create
}
}
describe("add") {
it("questions be save") {
// given
Questions.add(questionFixture)
// when
val q = Questions.findById(1)
// then
// assert!!!
}
}
}
我可以在before块中创建sesstion,然后在单元测试中使用会话吗?您可以使用createSession()并自己处理生命周期。我已经习惯了JUnit,我不知道您正在使用的测试框架的细节,但它应该是这样的:
// Don't import threadLocalSession, use this instead:
implicit var session: Session = _
before {
session = Database.forURL(...).createSession()
}
// Your tests go here
after {
session.close()
}
很管用。。我将ScalaTest与FunSpec一起使用,但没有什么问题。谢谢~