如何在Play框架和工具的单元测试中删除创建会话的代码 [英] how can I remove codes creating session in unit test for Play framework and slick
本文介绍了如何在Play框架和工具的单元测试中删除创建会话的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用play 2.0和slick.所以我为这样的模型编写单元测试.
I'm using play 2.0 and slick. so I write unit test for models like this.
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!!!
}
}
}
它运行良好,但是在每个单元测试中都会重复以下代码片段.
it works well but following snippets is dupulicated every unit test.
Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession {
Questions.ddl.create
// test code
}
所以,我想将这段代码移动到before块中,像这样.
so, I want to move this code to before block, somthing like this.
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块中创建会话,然后在单元测试中使用会话吗?
can I create sesstion in before block and then use the session in unit test?
推荐答案
您可以使用createSession()并自行处理生命周期.我已经习惯了JUnit,但不知道您使用的测试框架的细节,但是它看起来应该像这样:
You can use createSession() and handle the lifecycle yourself. I'm used to JUnit and I don't know the specifics of the test framework you're using but it should look something like this:
// Don't import threadLocalSession, use this instead:
implicit var session: Session = _
before {
session = Database.forURL(...).createSession()
}
// Your tests go here
after {
session.close()
}
这篇关于如何在Play框架和工具的单元测试中删除创建会话的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文