gpt4 book ai didi

scala - 异步断言未在 scalatest 中触发

转载 作者:行者123 更新时间:2023-12-01 13:46:35 24 4
gpt4 key购买 nike

我正在尝试编写一个测试来检查是否设置了正确的数据库,但断言永远不会触发,并且一切都成功结束(即使它应该失败):

import anorm._
import org.scalatestplus.play._
import play.api.db.DB

class Housekeeping extends PlaySpec with OneServerPerSuite {

// Make sure the test database is loaded
"test connection to test database" in {

DB.withConnection { implicit connection =>
SQL("SELECT * FROM accounts WHERE ID = 1").withResult(res => {
val row = res.head.row
val name = row.asMap("accounts.name")
println(name) // Prints to console
name mustEqual "this should fail"
println("HERE") // Never prints to console
})
}
}
}

控制台:

[info] Housekeeping:
[info] - application - Creating Pool for datasource 'default'
tyler
[info] - test connection to test database
[info] - application - Shutting down connection pool.

我不确定为什么什么都没有发生,因为我从数据库中得到了正确的名称。我找不到任何关于执行异步测试的文档,我认为这可能是问题的一部分。

最佳答案

类似于 this可以帮助:

import org.scalatest._
import concurrent.AsyncAssertions

import anorm._
import org.scalatestplus.play._
import play.api.db.DB

class Housekeeping extends PlaySpec with OneServerPerSuite with AsyncAssertions {

// Make sure the test database is loaded
"test connection to test database" in {
val w = new Waiter
DB.withConnection { implicit connection =>
SQL("SELECT * FROM accounts WHERE ID = 1").withResult(res => {
val row = res.head.row
val name = row.asMap("accounts.name")
println(name) // Prints to console
w { name mustEqual "this should fail" }
w.dismiss()
println("HERE")
})
}
w.await()
}
}

您的问题是 scalatest 没有收到 mustEqual 引发的异常,因为它是异步抛出的。

实际上 Waiter 是一种围绕 Promise 的包装器(所以你必须执行 dismiss() 才能完成它)和 w.await() 只是等待它并将异常从 w{...} 重定向到 scalatest 的线程。

关于scala - 异步断言未在 scalatest 中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35567820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com