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

时间:2012-09-14 18:10:52

标签: java selenium junit junit4 selenium-webdriver

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

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

想法?

3 个答案:

答案 0 :(得分: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));

这对你的问题有用吗?

答案 1 :(得分:6)

如果您想在运行中快速将此行为添加到 ALL 您的测试中,您可以使用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));

答案 2 :(得分:1)

如果要对测试失败进行截图,请添加此类

import java.io.File;

import java.io.IOException;

import java.util.UUID;

import org.apache.commons.io.FileUtils;

import org.junit.rules.MethodRule;

import org.junit.runners.model.FrameworkMethod;

import org.junit.runners.model.Statement;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

public class ScreenShotOnFailure implements MethodRule {

    private WebDriver driver;

    public ScreenShotOnFailure(WebDriver driver){
        this.driver = driver;
    }

    public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try {
                    statement.evaluate();
                } catch (Throwable t) {
                    captureScreenShot(frameworkMethod.getName());
                    throw t;
                }
            }

            public void captureScreenShot(String fileName) throws IOException {
                File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                fileName += UUID.randomUUID().toString();
                File targetFile = new File("./Screenshots/" + fileName + ".png");
                FileUtils.copyFile(scrFile, targetFile);
            }
        };
    }
}

在进行所有测试之前,您应使用以下规则:

@Rule
public ScreenShotOnFailure failure = new ScreenShotOnFailure(driver));

@Before
public void before() {
   ...
}