2016-02-23 47 views
2

我想寫一個測試,只是檢查,看看是否設置了正確的數據庫,但斷言永遠不會觸發,並且一切都成功結束(即使它應該失敗):異步斷言沒有在scalatest發射

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. 

我不知道爲什麼什麼也沒發生,因爲我從DA獲得名細tabase。我找不到任何關於執行異步測試的文檔,我認爲這可能是問題的一部分。

回答

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發射例外,因爲它是異步引發。

實際上Waiter是一種包裝的周圍Promise(所以你要做的dismiss()爲了完成它),w.await()只是等待它從w{...}異常重定向到scalatest的線程。

+0

太棒了,這正是我所尋找的 – Tyler