我正在使用 play 2.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)
// when
val q = Questions.findById(1)
// then
// assert!!!
}
}
}
它运行良好,但每个单元测试都会重复以下代码段。
Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession {
Questions.ddl.create
// test code
}
所以,我想将这段代码移动到 block 之前,像这样。
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 block 中创建 session ,然后在单元测试中使用该 session 吗?
最佳答案
您可以使用 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()
}
关于scala - 如何删除在 Play 框架和 slick 的单元测试中创建 session 的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16758228/