annedroiid annedroiid - 10 months ago 53
Scala Question

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

I have a test suite that implements

, and I'd ideally like to be able to check in my
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 Source

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 =
      info(s"The test '${}' failed")
      info(s"The test name is $nameLen characters long")
    case other => other

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