问题
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
}
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!!!
}
}
}
can I create sesstion in before block and then use the session in unit test?
回答1:
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()
}
来源:https://stackoverflow.com/questions/16758228/how-can-i-remove-codes-creating-session-in-unit-test-for-play-framework-and-slic