【问题标题】:How to configure ScalaTest to abort a suite if a test fails?如果测试失败,如何配置 ScalaTest 以中止套件?
【发布时间】:2014-11-18 01:19:22
【问题描述】:

我正在使用带有 SBT 0.13.5 的 ScalaTest 2.1.4。如果单个测试失败(多 JVM Akka 测试),我有一些长时间运行的测试套件可能需要很长时间才能完成。如果其中任何一个失败,我希望整个套件中止,否则套件可能需要很长时间才能完成,尤其是在我们的 CI 服务器上。

如果套件中的任何测试失败,我如何配置 ScalaTest 以中止套件?

【问题讨论】:

    标签: scala scalatest


    【解决方案1】:

    如果您只需要取消与失败测试相同的规范/套件/测试中的测试,则可以使用 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!")
      }
    
    }
    

    【讨论】:

    • 这很棒。现在,如果我将我的初始化内容(我既设置了数据库又测试设置功能是否正常工作)放在第一个套件中,我能保证它总是首先运行吗?即运行顺序和源文件中的顺序一样吗?​​
    【解决方案2】:

    谢谢尤金;这是我的改进:

    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"
    }
    

    不知道是否可以不使用vars。

    【讨论】:

      猜你喜欢
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 2018-08-18
      • 1970-01-01
      • 2013-08-06
      • 2012-07-15
      • 2016-04-26
      • 1970-01-01
      相关资源
      最近更新 更多