首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Selenium可以在JUnit测试失败时截屏吗?

Selenium可以在JUnit测试失败时截屏吗?
EN

Stack Overflow用户
提问于 2012-09-15 02:10:52
回答 2查看 27.6K关注 0票数 21

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

不,我不想去编辑我们无数的测试来添加try/catch。我想,我可能,只是可能被说成是一个注解。我所有的测试都有一个共同的父类,但我想不出有什么可以解决这个问题的。

想法?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-09-18 12:24:45

几次快速搜索后,我找到了这个:

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));

这对你的问题有效吗?

票数 18
EN

Stack Overflow用户

发布于 2020-07-05 18:08:31

如果您想在测试失败时截图,请添加这个类

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() {
   ...
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12429793

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档