当我的测试用例失败时,尤其是在我们的构建服务器上,我想拍一张屏幕的照片/屏幕截图,以帮助我调试后面发生的事情。我知道如何截图,但我希望在浏览器关闭之前,如果测试失败,可以在JUnit中调用我的takeScreenshot()
方法。
不,我不想去编辑我们无数的测试来添加try/catch。我想,我可能,只是可能被说成是一个注解。我所有的测试都有一个共同的父类,但我想不出有什么可以解决这个问题的。
想法?
发布于 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));
这对你的问题有效吗?
发布于 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() {
...
}
https://stackoverflow.com/questions/12429793
复制相似问题