【问题标题】:How to use JUnit's @Rule annotation with Scala Specs2 tests?如何在 Scala Specs2 测试中使用 JUnit 的 @Rule 注释?
【发布时间】:2014-12-17 23:13:01
【问题描述】:

在我们的项目中,我们将 Scala Specs2 与 Selenium 一起使用。 我正在尝试使用 JUnit 注释为我的测试实现屏幕截图失败机制“in a classic way (link)”,但是,该规则根本不会调用测试失败。

测试结构如下:

class Tests extends SpecificationWithJUnit{

      trait Context extends LotsOfStuff {
        @Rule
        val screenshotOnFailRule = new ScreenshotOnFailRule(driver)
      }

      "test to verify stuff that will fail" should {
        "this test FAILS" in new Context {
         ...
      }
}

ScreenshotOnFailRule 如下所示:

class ScreenshotOnFailRule (webDriver: WebDriver) extends TestWatcher {

  override def failed(er:Throwable, des:Description) {
    val scrFile = webDriver.asInstanceOf[TakesScreenshot].getScreenshotAs(OutputType.FILE)
    FileUtils.copyFile(scrFile, new File(s"/tmp/automation_screenshot${Platform.currentTime}.png"))
  }
}

我知道它现在可能不起作用,因为测试没有使用 @Test 注释进行注释。 是否可以使用 JUnit @Rule 注释来注释 Specs2 测试?

【问题讨论】:

    标签: scala selenium junit selenium-webdriver specs2


    【解决方案1】:

    根据this question,似乎不支持 JUnit 规则。但是你可以尝试使用AroundExample trait:

    import org.specs2.execute.{AsResult, Result}
    import org.specs2.mutable._
    import org.specs2.specification.AroundExample
    
    class ExampleSpec extends Specification with AroundExample {
    
      // execute tests in sequential order
      sequential
    
      "The 'Hello world' string" should {
        "contain 11 characters" in  {
          "Hello world" must have size (10)
        }
    
       // more tests..
      }
    
      override protected def around[T](t: => T)(implicit ev: AsResult[T]): Result = {
        try {
          AsResult.effectively(t)
        } catch {
          case e: Throwable => {
            // take screenshot here
            throw e
          }
        }
      }
    }
    

    【讨论】:

    • 谢谢,但这对我不起作用。看起来 MyNotifier 没有注册失败 - 测试失败时不会调用 exampleFailure 方法。请问有什么建议吗?你能在你的机器上试试吗?
    • 请注意,您必须完全限定在报告参数中对通知程序的引用。例如,如果您的规范和通知程序都放在包mytest 中,您需要编写args.report(notifier = "mytest.MyNotifier")。我已经相应地更新了答案。
    • 好的,现在我看到了一些进展。事件“specStart”正常工作(“specEnd”不是......)。但是,仍然有一些我不明白的问题:1)我所有的测试都执行了两次。第一次“正常”运行,在第二次运行中,通知程序(MyNotifier)似乎在执行它们。 2) 我如何找到需要的事件?就我而言,我想“捕捉”测试失败事件,而 exampleError 是,好吧,例子 :)
    • 您的测试没有执行两次。您的通知者只会在相应事件发生时收到通知。所以为了在发生故障时得到通知,你只需要实现exampleFailure。不要被名称混淆,因为这是规范术语。
    • 如有疑问,请查看this gist
    猜你喜欢
    • 2014-08-26
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多