我有一个selenium项目,它通过testng运行并行测试。当测试失败时,我有一个监听器类来捕捉屏幕截图。这门课如下
public class ScreenshotOnFailure extends TestListenerAdapter {
@Override
public void onTestFailure(ITestResult tr) {
WebDriver driver = SeleniumSetup.driverrunning;
boolean hasQuit = driver.toString().contains("(null)");
if(!hasQuit){
System.out.println(driver);
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy__hh_mm_ssaa");
Date date = new Date();
String NewFileNamePath = null;
File directory = new File(".");
String methodName = tr.getMethod().getMethodName();
try {
NewFileNamePath =directory.getCanonicalPath() + "\\target\\surefire-reports\\html\\Screenshots\\"+methodName+"_"+ dateFormat.format(date) +"Listener.png";
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileUtils.copyFile(scrFile, new File(NewFileNamePath));
} catch (IOException e) {
e.printStackTrace();
}
String reportFilePath = ".\\Screenshots\\"+methodName+"_"+ dateFormat.format(date) +".png";
System.setProperty("org.uncommons.reportng.escape-output", "false");
Reporter.log("<a href=" + reportFilePath + ">Click to open screenshot</a><img src=" + reportFilePath + " height='350' width='700'>");
}
}}在我的测试中,我有一个AfterMethod来清理测试
@AfterMethod(alwaysRun = true)
public void tearDown() throws Exception
{
driver.quit();
}如果一个接一个地运行测试,那么将捕获正确的浏览器屏幕截图,但是,如果我运行并行测试,则会捕获错误的测试浏览器。我认为问题可能有以下几点之一
我有一个解决办法,它非常喜欢创建一个静态屏幕捕捉对象,然后将它添加到AfterMethod中,但是这并不理想,因为我想使用一个侦听器。
发布于 2016-09-23 18:39:27
从您的代码WebDriver driver = SeleniumSetup.driverrunning来看,driverrunning似乎是SeleniumSetup类中的静态驱动实例。因此,在并行执行中,它可能引用错误的驱动程序对象。
ThreadLocal可以帮助您创建线程安全驱动程序对象,下面是一个示例。
public class DriverFactory
{
private DriverFactory()
{
//Do-nothing..Do not allow to initialize this class from outside
}
private static DriverFactory instance = new DriverFactory();
public static DriverFactory getInstance()
{
return instance;
}
ThreadLocal<WebDriver> driver = new ThreadLocal<WebDriver>() // thread local driver object for webdriver
{
@Override
protected WebDriver initialValue()
{
return new FirefoxDriver(); // can be replaced with other browser drivers
}
};
public WebDriver getDriver() // call this method to get the driver object and launch the browser
{
return driver.get();
}
public void removeDriver() // Quits the driver and closes the browser
{
driver.get().quit();
driver.remove();
}
}使用DriverFactory获取驱动程序实例。
WebDriver driver = DriverFactory.getInstance().getDriver();https://stackoverflow.com/questions/39666408
复制相似问题