【问题标题】:Is there a way in a Scala after() method to know whether the test failed?Scala after() 方法中有没有办法知道测试是否失败?
【发布时间】:2016-11-22 17:45:37
【问题描述】:

我有一个实现BeforeAndAfter 的测试套件,如果测试失败,我希望能够检查我的after() 方法,如果它确实计算了一些值并将其打印出来。有内置的方法吗?

ps。我知道我可以在整个测试中进行尝试/捕捉,但我宁愿不必这样做。

【问题讨论】:

    标签: scala scalatest


    【解决方案1】:

    我认为您不能在 after() 中执行此操作,但是您可以通过覆盖 withFixture() 来执行此操作。此方法运行实际测试,之后您可以匹配结果并在失败时打印一些内容:

    class ExampleSpec extends WordSpec with MustMatchers {
    
      "Example" must {
        "work correctly" in {
          3 must be(3)
        }
    
        "not fail" in {
          true must be(false)
        }
      }
    
      override def withFixture(test: NoArgTest) = super.withFixture(test) match {
        case failed: Failed =>
          val nameLen = test.name.length
          info(s"The test '${test.name}' failed")
          info(s"The test name is $nameLen characters long")
          failed
        case other => other
      }
    }
    

    参见Sharing Fixtures,尤其是“Overriding withFixture(NoArgTest)”部分

    【讨论】:

    • 谢谢,这正是我要找的东西
    【解决方案2】:

    根据您的需要,您可以:

    1) 写def around[T](code: => T) = try {code} ... 之类的东西并像这样使用它:

        test("mytest") {
           around {
    
           }
        }
    
        it should "blabla" in around {
           ...
        }
    

    2) 如果您不使用规范,那么只需编写您自己的规范:

        def mytest[T](name: String)(code: =>T) = test(name){
          try {
            code
          } ...
        }
    

    或者直接覆盖test:

       override def test[T](name: String)(code: =>T) = super.test(name){
          try {
            code
          } ...
        }
    

    两者都可以在单独的 trait 中完成,顺便说一句。

    3) 覆盖withFixture,因为它描述了@alextsc 的答案

    4) 如果您想拦截构建中的所有测试,请编写自己的 reporter

    附: BeforeAndAfter/withFixture 旨在清理资源(这就是为什么它们不让您访问异常),因此如果您需要分析和表示错误,从逻辑上讲,报告器解决方案可能更适合,但它不太方便。

    【讨论】:

      猜你喜欢
      • 2019-05-08
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 2010-12-24
      • 2023-03-18
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      相关资源
      最近更新 更多