【问题标题】:Screenshot on every failure using Scalatest使用 Scalatest 的每次失败的屏幕截图
【发布时间】:2017-01-08 23:57:10
【问题描述】:
我想使用 ScalaTest 在 Spec 或 Suite 中为每个失败的测试截屏。
Scala 测试网站展示了如何围绕每个可能失败的代码截取屏幕截图:
withScreenshot {
drive.findElement(By.id("login")).getAttribute("value") should be ("Login")
}
有this post 试图解释,但我不明白究竟应该做什么。
我还找到了 ScreenshotOnFailure.scala 类,但是一旦它是私有的并且有包限制,就无法使用它。
谁能告诉我是否有办法拦截任何故障然后截图?
【问题讨论】:
标签:
scala
screenshot
scalatest
【解决方案1】:
为了得到最终答案,我正在编写基于问题中提到的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: 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")
}
}
}
}
从现在开始,所有扩展 Screenshot trait 的 Specs 都会拦截错误并保存屏幕截图。
作为补充,withScreenshot() 的周围区域,如问题中所述,仅保存断言失败,但当测试因未找到元素(例如错误的选择器)而失败时,它不会保存屏幕截图。
使用上面的代码,所有失败都会保存截图。