如何使用JUnit';使用Scala Specs2测试的s@规则注释?

如何使用JUnit';使用Scala Specs2测试的s@规则注释?,scala,selenium,junit,selenium-webdriver,specs2,Scala,Selenium,Junit,Selenium Webdriver,Specs2,在我们的项目中,我们使用Scala Specs2和Selenium。 我试图使用JUnit注释为我的测试实现失败机制“”的屏幕截图,但是,该规则根本不调用测试失败 试验的结构如下所示: class Tests extends SpecificationWithJUnit{ trait Context extends LotsOfStuff { @Rule val screenshotOnFailRule = new ScreenshotOnFailR

在我们的项目中,我们使用Scala Specs2和Selenium。 我试图使用JUnit注释为我的测试实现失败机制“”的屏幕截图,但是,该规则根本不调用测试失败

试验的结构如下所示:

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"))
  }
}
我知道现在它可能不起作用了,因为测试没有用@testannotation注释。 是否可以使用JUnit@Rule annotation对Specs2测试进行注释?

根据这一点,JUnit规则似乎不受支持。但是您可以尝试利用
AroundExample
特性:

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是,嗯,example:)您的测试不会执行两次。您的通知程序只会在相应事件发生时收到通知。因此,为了在发生故障时得到通知,您只需要实现
examplefilure
。不要被名称搞混,因为这是规范术语。如果有疑问,请检查。