如何在Play框架和光滑的单元测试中删除创建会话的代码

Out*_*der 3 scala playframework slick playframework-2.1

我正在使用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!!!
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但是每个单元测试后都会重复使用片段.

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

所以,我想把这段代码移到块之前,就像这样.

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!!!
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我可以在块之前创建sesstion然后在单元测试中使用会话吗?

sze*_*ger 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()
}
Run Code Online (Sandbox Code Playgroud)