Selenium 截图监听器抓取错误的浏览器

Selenium screenshot listener captures the wrong browser

我有一个 selenium 项目运行通过 testng 进行并行测试。当测试失败时,我有一个捕获屏幕截图的侦听器 class。 class如下

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,但是这不太理想,因为我想使用侦听器。

从您的代码 WebDriver driver = SeleniumSetup.driverrunning 来看,driverrunning 似乎是 SeleniumSetup class 中的静态驱动程序实例。因此,在并行执行中,它可能会引用错误的驱动程序对象。

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