在 h2 数据库上断言唯一键约束,具有光滑和标量测试



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

首先测试

"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)
}

也许在 2 列上的这种唯一约束在 h2 中甚至是不可能的?

无论如何:

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

实际结果:成功的测试:(

编辑:另外,我使用这个:

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

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

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

最新更新