测试不起作用后关闭或关闭 H2 数据库

Close or shutdown of H2 database after tests is not working

在每次测试后将 scalatest 与 Slick 一起使用时,我遇到了数据库清理问题。

测试代码如下:

class H2DatabaseSpec extends WordSpec with Matchers with ScalaFutures with BeforeAndAfter {
  implicit override val patienceConfig = PatienceConfig(timeout = Span(5, Seconds))

  val h2DB: H2DatabaseService = new H2DatabaseService
  var db: Database = _

  before {
    db = Database.forConfig("h2mem1")
    h2DB.createSchema.futureValue
  }

  after {
    db.shutdown.futureValue
  }

  "H2 database" should {
    "query a question" in {
      val newQuestion: QuestionEntity = QuestionEntity(Some(1L), "First question")
      h2DB.insertQuestion(newQuestion).futureValue

      val question = h2DB.getQuestionById(1L)

      question.futureValue.get shouldBe newQuestion
    }
  }

  it should {
    "query all questions" in {
      val newQuestion: QuestionEntity = QuestionEntity(Some(2L), "Second question")
      h2DB.insertQuestion(newQuestion).futureValue

      val questions = h2DB.getQuestions

      questions.futureValue.size shouldBe 1
    }
  }
}

数据库服务只是在定义的数据库上调用 run 方法:

class H2DatabaseService {

  val db = Database.forConfig("h2mem1")

  val questions = TableQuery[Question]

  def createSchema =
    db.run(questions.schema.create)

  def getQuestionById(id: Long): Future[Option[QuestionEntity]] =
    db.run(questions.filter(_.id === id).result.headOption)

  def getQuestions: Future[Seq[QuestionEntity]] =
    db.run(questions.result)

  def insertQuestion(question: QuestionEntity): Future[Int] =
    db.run(questions += question)
}

class Question(tag: Tag) extends Table[QuestionEntity](tag, "QUESTION") {
  def id = column[Option[Long]]("QUESTION_ID", O.PrimaryKey, O.AutoInc)
  def title = column[String]("TITLE")

  def * = (id, title) <> ((QuestionEntity.apply _).tupled, QuestionEntity.unapply)
}

case class QuestionEntity(id: Option[Long] = None, title: String) {
  require(!title.isEmpty, "title.empty")
}

并且数据库定义如下:

h2mem1 = {
  url = "jdbc:h2:mem:test1"
  driver = org.h2.Driver
  connectionPool = disabled
  keepAliveConnection = true
}

我正在使用 Scala 2.11.8、Slick 3.1.1、H2 数据库 1.4.192 和 scalatest 2.2.6。

执行测试时出现的错误是Table "QUESTION" already exists。所以看起来 shutdown() 方法根本没有效果(但它被调用 - 在调试器中检查)。

有人知道如何处理这种情况吗?如何在每次测试后正确清理数据库?

由于在不同的对象上调用方法,数据库没有被正确清理。

H2DatabaseService 有它自己的 db 对象和它自己的测试。重构 H2 数据库服务并调用后问题得到解决:

after {
  h2DB.db.shutdown.futureValue
}