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

Rya*_*ton 19 java junit selenium junit4 selenium-webdriver

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

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

想法?

Jef*_*ica 18

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

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

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

imageFileOutputStream.write(
    ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));
Run Code Online (Sandbox Code Playgroud)

这对你的问题有用吗?

  • 以下文章介绍了如何使用TestWatcher截取屏幕截图:http://www.thinkcode.se/blog/2012/07/08/performing-an-action-when-a-test-fails我发现它比杰夫提到的文章. (2认同)

del*_*ala 6

如果要在运行中快速将此行为添加到所有测试中,可以使用该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
    }

}
Run Code Online (Sandbox Code Playgroud)

像这样将侦听器添加到测试运行器中......

JUnitCore junit = new JUnitCore();
junit.addListener(new ScreenshotListener((TakesScreenShots) webDriver));

// then run your test...

Result result = junit.run(Request.classes(FullTestSuite.class));
Run Code Online (Sandbox Code Playgroud)