想象一下以下场景:你有一本由有序章节组成的书。
首先测试:
"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
中甚至不可能对2列进行这样的唯一约束?
反正:
期望: 抛出一个异常,然后我可以在我的测试中拦截/期望,因此现在是一个失败的测试,因为它违反了一个唯一约束。
实际结果: 一次成功的测试:(
编辑:另外,我用这个:
implicit val defaultPatience =
PatienceConfig(timeout = Span(30, Seconds), interval = Span(100, Millis))
答案 0 :(得分:2)
db.run
返回Future
。
您必须Await
才能获得执行结果。
试试这个:
import scala.concurrent.duration._
val future = db.run(...)
Await.result(future, 5 seconds)