3

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?

4

1 回答 1

5

您可以使用 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()
}
于 2013-05-26T20:19:54.703 回答