在断言之前等待插入完成

Await insert to finish before asserting

我有一个模型并在开始之前编写了测试。现在我的问题是:虽然功能有效,但我的测试是不确定的。大多数时候他们工作,但有时他们不工作。我认为这是因为 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 "expected length was 2, actual 0"。如前所述,对我来说,这里看起来像 "race condition"(我知道那不是正确的终点;))。

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

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

但这并没有改变任何事情。那是为什么呢?有人可以向我解释为什么 Await 不阻塞这里吗?我假设这会阻止并仅执行插入已执行后的行。

我还尝试将断言包装在 .onComplete 块中,但也没有成功。

对我有什么提示吗?

我怀疑你的问题是有时你的 before 钩子也没有完成,因为它也是异步的。我怀疑如果你在 before 块中添加一个 Await.ready 到你的 future 以及你的 setup 块,问题就会消失。