2014-09-23 81 views
4

我使用ScalaTest 2.1.4和SBT 0.13.5。我有一些長期運行的測試套件,如果單個測試失敗可能需要很長時間才能完成(多JVM Akka測試)。如果其中任何一個失敗,我希望整個套件中止,否則套件可能需要很長時間才能完成,特別是在我們的CI服務器上。如何配置ScalaTest以在測試失敗時中止套件?

如何在套件中的任何測試失敗時將ScalaTest配置爲中止套件?

回答

4

如果您只需要取消相同規格/套件/測試的測試作爲失敗測試,​​則可以使用scalatest中的CancelAfterFailure混合。如果你想全局取消它們,例如:

import org.scalatest._ 


object CancelGloballyAfterFailure { 
    @volatile var cancelRemaining = false 
} 

trait CancelGloballyAfterFailure extends SuiteMixin { this: Suite => 
    import CancelGloballyAfterFailure._ 

    abstract override def withFixture(test: NoArgTest): Outcome = { 
    if (cancelRemaining) 
     Canceled("Canceled by CancelGloballyAfterFailure because a test failed previously") 
    else 
     super.withFixture(test) match { 
     case failed: Failed => 
      cancelRemaining = true 
      failed 
     case outcome => outcome 
     } 
    } 

    final def newInstance: Suite with OneInstancePerTest = throw new UnsupportedOperationException 
} 

class Suite1 extends FlatSpec with CancelGloballyAfterFailure { 

    "Suite1" should "fail in first test" in { 
    println("Suite1 First Test!") 
    assert(false) 
    } 

    it should "skip second test" in { 
    println("Suite1 Second Test!") 
    } 

} 

class Suite2 extends FlatSpec with CancelGloballyAfterFailure { 

    "Suite2" should "skip first test" in { 
    println("Suite2 First Test!") 
    } 

    it should "skip second test" in { 
    println("Suite2 Second Test!") 
    } 

} 
+0

這太好了。現在,如果我在第一個套件中放置我的初始化資料(我既設置了數據庫又測試了設置功能),我保證它始終會首先運行?即運行順序與源文件中的順序相同嗎? – akauppi 2014-10-24 13:22:08

0

謝謝尤金;這裏是我的改進:

trait TestBase extends FunSuite { 
    import TestBase._ 

    override def withFixture(test: NoArgTest): Outcome = { 
    if (aborted) Canceled(s"Canceled because $explanation") 
    else super.withFixture(test) 
    } 

    def abort(text: String = "one of the tests failed"): Unit = { 
    aborted = true 
    explanation = text 
    } 
} 

object TestBase { 
    @volatile var aborted = false 
    @volatile var explanation = "nothing happened" 
} 

不知是否可以在不使用var s內完成。

相關問題