【问题标题】:Asynchronous assertion is not firing in scalatest异步断言未在 scalatest 中触发
【发布时间】:2016-02-23 02:43:20
【问题描述】:

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

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.

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

【问题讨论】:

    标签: scala unit-testing playframework anorm


    【解决方案1】:

    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 触发的异常,因为它是异步抛出的。

    实际上WaiterPromise 的一种包装器(因此您必须执行dismiss() 才能完成它)并且w.await() 只是等待它并将异常从w{...} 重定向到scalatest线程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 2014-01-22
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      • 2018-01-22
      相关资源
      最近更新 更多