annedroiid annedroiid - 15 days ago 5
Scala Question

Is there a way in a Scala after() method to know whether the test failed?

I have a test suite that implements

BeforeAndAfter
, and I'd ideally like to be able to check in my
after()
method if the test failed, and if it did calculate some value and print it out. Is there an inbuilt way of doing this?

ps. I know I can do a try/catch around the whole test but I'd rather not have to do that.

Answer

I don't think you can do it in after(), however you can do it by overriding withFixture(). This method runs the actual test, after that you can match the result and print something in case of failure:

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

See Sharing Fixtures, especially the section "Overriding withFixture(NoArgTest)"