在 Scala after() 方法中有没有办法知道测试是否失败?

ann*_*iid 2 scala scalatest

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

附:我知道我可以在整个测试中尝试/捕获,但我宁愿不必这样做。

小智 5

我不认为你可以在 中做到这一点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
  }
}
Run Code Online (Sandbox Code Playgroud)

请参阅共享夹具,尤其是“覆盖与夹具(NoArgTest)”部分