【问题标题】:Assert unique key constraint on h2 database with slick and scalatest使用 slick 和 scalatest 在 h2 数据库上断言唯一键约束
【发布时间】:2016-07-08 14:23:53
【问题描述】:

想象以下场景:您有一本由有序章节组成的书。

首先进行测试

"Chapters" should "have a unique order" in
{
    //  val exception = intercept
    db.run(
      DBIO.seq
      (
        Chapters.add(0, 0, "Chapter #0"),
        Chapters.add(0, 0, "Chapter #1")
      )
    )
}

现在是实现

case class Chapter(id: Option[Long] = None, bookId: Long, order: Long, val title: String) extends Model

class Chapters(tag: Tag) extends Table[Chapter](tag, "chapters")
{
  def id = column[Option[Long]]("id", O.PrimaryKey, O.AutoInc)
  def bookId = column[Long]("book_id")
  def order = column[Long]("order")
  def title = column[String]("title")

  def * = (id, bookId, order, title) <> (Chapter.tupled, Chapter.unapply)
  def uniqueOrder = index("order_chapters", (bookId, order), unique = true)

  def bookFK = foreignKey("book_fk", bookId, Books.all)(_.id.get, onUpdate = ForeignKeyAction.Cascade, onDelete = ForeignKeyAction.Restrict)
}

也许在h2 中甚至不可能对两列进行这样的唯一约束?

无论如何:

预期: 抛出一个异常,然后我可以在我的测试中拦截/预期,因此现在测试失败,因为违反了唯一约束。

实际结果: 测试成功:(

edit:另外,我用这个:

implicit val defaultPatience = PatienceConfig(timeout = Span(30, Seconds), interval = Span(100, Millis))

【问题讨论】:

  • 你看不到生成的架构吗?检查 h2 本身内部的表定义

标签: scala tdd h2 slick scalatest


【解决方案1】:

db.run 返回一个Future。 您必须在其上Await 才能获得执行结果。 试试这个:

 import scala.concurrent.duration._
 val future = db.run(...)
 Await.result(future, 5 seconds)

【讨论】:

  • 我可能应该提到这一点:implicit val defaultPatience = PatienceConfig(timeout = Span(30, Seconds), interval = Span(100, Millis))
  • 我不明白这对任何事情有什么影响
  • 我从来没有在我的测试中使用 await 并且总是默认的耐心。 artima.com/docs-scalatest-2.0.M5/org/scalatest/concurrent/…
  • 你不需要等待,只要你不期望同步检查返回的对象的异常(即不在.map.onSuccess等内部)
  • 这就是我所缺少的,谢谢。我会尽快测试
猜你喜欢
  • 1970-01-01
  • 2017-05-21
  • 2015-05-07
  • 2017-12-07
  • 2016-06-04
  • 2011-05-28
  • 2013-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多