how can I remove codes creating session in unit test for Play framework and slick

点点圈 提交于 2019-12-12 15:04:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!