在断言之前等待插入完成



我有一个模型,并在开始之前编写了测试。现在我的问题是:虽然功能可以工作,但我的测试是不确定的。大多数时候它们都有效,但有时也不行。我想这是因为Future

让我们用例子来说明我的意思:

before {
    db.run(animals.createTable)
  }
  after {
    db.run(animals.dropTable)
  }
  "An animal" must "have a unique id" in
  {
    val setup =  DBIO.seq(
      animals.insert(Animal("Ape")),
      animals.insert(Animal("Dog"))
    )
    db.run(setup)

    val result = db.run(animals.tableQuery.result).futureValue
    result shouldBe a[Seq[_]]
    result distinct.length shouldEqual 2
    result(0).id should not equal result(1).id
  }

我假设有时db.run(setup)及时完成,但有时没有,因此我得到AssertionException"预期长度为2,实际为0"。如前所述,对我来说,这里看起来像一个"竞争条件"(我知道这不是正确的终点;))。

所以,我所尝试的只是等待插入语句的结果,像这样:

Await.ready(db.run(setup), Duration.Inf)

但这改变不了什么。为什么呢?有人能告诉我为什么Await在这里不阻塞吗?

我还尝试在.onComplete块中包装断言,但也没有运气。

有什么提示吗?

我怀疑你的问题是,有时你的before钩子还没有完成,因为它也是异步的。我怀疑,如果您在before块中添加Await.ready到您的未来,那么问题就会消失。

最新更新