How to remove code creating a session in unit test for Play and slick platforms

I am using play 2.0 and slick. therefore I am writing unit test for such models.

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 the following snippets are duplicated every unit test.

 Database.forURL("jdbc:h2:mem:test1", driver = "org.h2.Driver") withSession { Questions.ddl.create // test code } 

therefore, I want to move this code to a block, something 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 a scene in front of the block and then use the session in unit test?

+3
source share
1 answer

You can use createSession () and handle the life cycle yourself. I'm used to JUnit and I donโ€™t know the specifics of the test environment used, 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() } 
+5
source

All Articles