Selenium可以使用JUnit截取测试失败的截图吗?

当我的测试用例失败时,特别是在我们的构建服务器上,我想拍一张屏幕的图片/截图来帮助我调试以后发生的事情。 我知道如何截取屏幕截图,但我希望在浏览器关闭之前,如果测试失败,JUnit中的方法可以调用我的takeScreenshot()方法。

不,我不想编辑我们的bazillions测试来添加try / catch。 我想也许,也许可能会被说成一个注释。 我的所有测试都有一个共同的父类,但我想不出我能做什么来解决这个问题。

想法?

一些快速搜索让我想到了这个:

http://blogs.steeplesoft.com/posts/2012/grabbing-screenshots-of-failed-selenium-tests.html

基本上,他建议创建一个JUnit4 Rule ,它将test Statement包装在try / catch块中,并在其中调用:

 imageFileOutputStream.write( ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES)); 

这对您的问题有用吗?

如果要在运行中快速将此行为添加到所有测试中,可以使用RunListener接口侦听测试失败。

 public class ScreenshotListener extends RunListener { private TakesScreenshot screenshotTaker; @Override public void testFailure(Failure failure) throws Exception { File file = screenshotTaker.getScreenshotAs(OutputType.File); // do something with your file } } 

像这样将监听器添加到测试运行器中……

 JUnitCore junit = new JUnitCore(); junit.addListener(new ScreenshotListener((TakesScreenShots) webDriver)); // then run your test... Result result = junit.run(Request.classes(FullTestSuite.class));