我正在尝试将失败的methodName添加到使用Java运行selenium时发生故障时拍摄的屏幕截图。香港专业教育学院尝试了多种解决方案,但它们都返回了规则类或methodName的methodName。我不确定如何制作,因此屏幕快照文件名返回“ shouldFail_date.png”。
package test;
import org.apache.commons.io.FileUtils;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ScreenShotRule extends TestWatcher {
private WebDriver browser;
public ScreenShotRule(WebDriver browser) {
this.browser = browser;
}
@Override
protected void failed(Throwable e, Description description) {
TakesScreenshot takesScreenshot = (TakesScreenshot) browser;
File scrFile = takesScreenshot.getScreenshotAs(OutputType.FILE);
File destFile = getDestinationFile();
try {
FileUtils.copyFile(scrFile, destFile);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
@Override
protected void finished(Description description) {
browser.close();
}
private File getDestinationFile() {
Throwable t = new Throwable();
String callerMethodName = t.getStackTrace()[1].getMethodName();
DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy");
String userDirectory = "screenshots/" + dateFormat.format(new Date()) + "/";
new File(userDirectory).mkdirs();
String absoluteFileName = userDirectory callerMethodName + dateFormat.format(new Date()) + ".png";
return new File(absoluteFileName);
}
}
package test;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ScreenShotTest {
private WebDriver browser = new FirefoxDriver();
@Rule
public ScreenShotRule screenShootRule = new ScreenShotRule(browser);
@Test
public void shouldFail() {
browser.get("http://www.google.com");
By link = By.partialLinkText("I do not expect to find a link with this text");
browser.findElement(link);
}
}
最佳答案
您可以使用基于testng的有效selenium testing-frameworks-ISFW之一,并根据您的需要提供描述性报告。这是一些快照
Overview
Detail Report