异步断言不会在scalatest中触发

时间:2016-02-23 02:43:20

标签: scala unit-testing playframework anorm

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

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.

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

1 个答案:

答案 0 :(得分:3)

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{...}到最新线程的异常。