【问题标题】:Close or shutdown of H2 database after tests is not working测试不工作后关闭或关闭 H2 数据库
【发布时间】:2017-01-10 07:12:16
【问题描述】:

在使用 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() 方法根本没有效果(但它被调用了 - 在调试器中检查)。

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

【问题讨论】:

    标签: scala h2 slick scalatest


    【解决方案1】:

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

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

    after {
      h2DB.db.shutdown.futureValue
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-06
      • 2011-02-15
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      相关资源
      最近更新 更多