是否可以设置webdriver以便在遇到错误时可以进行屏幕捕获?
答案 0 :(得分:3)
如果您正在运行JUnit,则可以设置规则以在失败时截取屏幕截图。对于TestNG,有类似的方法。
<强> Event.java 强>
public static void takeScreenshot(WebDriver driver, String name) throws IOException {
if (driver instanceof TakesScreenshot) {
File tempFile = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(tempFile, new File(String.format("screenshots/%s.png", name)));
}
}
<强> ScreenshotOnFailRule.java 强>
public class ScreenshotOnFailRule extends TestWatcher {
private static boolean shouldStopTests = false;
@Override
public void failed(Throwable e, Description d) {
try {
Event.takeScreenshot(yourDriver, "Failure");
} catch (IOException ioe) {
log.error("Test didn't finish due to hard failure.");
shouldStopTests = true;
}
if (shouldStopTests) {
System.exit(0);
}
}
然后在测试课开始时:
@Rule
public TestRule screenshot = new ScreenshotOnFailRule();
答案 1 :(得分:0)
当然,这是可能的。这是一个例子:
WebDriver firefoxDriver = new FirefoxDriver();
firefoxDriver.get("http://www.google.com/");
File scrsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrsht, new File("your_path/screenshot.png"));