提问者:小点点

使用 Scalatest 的每个故障的屏幕截图


我想使用ScalaTest截屏Spec或Suite中的每个失败测试。Scala Test网站展示了如何围绕可能因此失败的每个代码截屏:

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

有这篇文章试图解释,但我不明白到底应该怎么做。我还找到了类ScreenshotOnFailure.scala,但是一旦它是私有的并且有包限制,就无法使用它。

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


共1个答案

匿名用户

为了得到一个最终的答案,我正在根据问题中提到的这篇文章中的方法,写下解决问题的方法。

简而言之,解决方案最终是这样的(伪代码)。

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: https://stackoverflow.com/questions/3422262/take-a-screenshot-with-selenium-webdriver
      }
      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")
         }
      }
   }
}

从这一点开始,所有扩展屏幕截图特征的规范都将拦截错误并保存屏幕截图。

作为补充,问题中提到的with Screenshot()的周边区域仅保存断言失败,但当测试因未找到元素(例如错误的选择器)而失败时,它不会保存屏幕截图。

使用上面的代码,所有失败都将保存一个屏幕截图。