使用 Scalatest 每次失败的截图

Screenshot on every failure using Scalatest

我想在使用 ScalaTest 的规范或套件中对每个失败测试进行截图。 Scala 测试网站展示了如何截取可能因此失败的每个代码的屏幕截图:

withScreenshot {
   drive.findElement(By.id("login")).getAttribute("value") should be ("Login")
}

this post试图解释,但我不明白到底应该做什么。 我也找到了 class ScreenshotOnFailure.scala,但是不能使用它,因为它是私有的并且有包限制。

谁能告诉我有没有办法拦截任何失败然后截图?

只是为了得到最终答案,我正在根据问题中提到的 this post 中的方法编写解决问题的方法。

总之,解决方案是这样的(伪代码)。

trait Screenshots extends FunSpec {
   ...

   override def withFixture(test: NoArgTest): Outcome = {
      val outcome = test()

      // If the test fails, it will hold an exception.
      // You can get the message with outcome.asInstanceOf[Failure].exception
      if (outcome.isExceptional) {
         // Implement Selenium code to save the image using a random name
         // Check: 
      }
      outcome
   }
}

class MySpec extends Screenshots {
   ...

   describe("Scenario A") {
      describe("when this") {
         it("the field must have value 'A'") {
            // It will save a screenshot either if the selector is wrong or the assertion fails
            driver.findElement(By.id("elementA")).getAttribute("value") should be ("A")
         }
      }
   }
}

从现在开始,所有扩展 Screenshot 特性的 Spec 将拦截错误并保存屏幕截图。

补充一下,如问题中所述,使用 withScreenshot() 的周围区域仅保存断言失败,但当由于未找到元素(例如错误的选择器)而导致测试失败时,它不会保存屏幕截图。

用上面的代码,所有失败都会截图保存。