使用TestNG运行并行测试时捕获WebDriver屏幕截图 [英] Capture WebDriver Screenshots When Running Parallel Tests With TestNG

查看:205
本文介绍了使用TestNG运行并行测试时捕获WebDriver屏幕截图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在通过分别重写TestListenerAdapter方法onTestFailure和onTestSuccess来捕获有关TestNG成功和失败的屏幕截图.为此,您需要指定要为其截屏的驱动程序.

I am currently capturing screenshots on failure and success in TestNG by way of overriding the TestListenerAdapter methods onTestFailure, and onTestSuccess respectively. In order to do this you need to specify which driver you want to take a screenshot of.

我的问题:在方法级别上并行运行测试时,是否有捕获截图的好方法?

My question: Is there a good way to capture screenshots when running tests in parallel on the method level?

为了并行运行测试,每个单独的测试都需要一个唯一的驱动程序实例.因此,在任何给定时间,您都有x个正在运行的驱动程序实例.当需要捕获屏幕截图时,如何确定要使用哪个驱动程序?

In order to run tests in parallel, each individual test needs a unique driver instance. So, at any given time you have x number of driver instances running. When it comes time to capture a screenshot, how do you determine which driver to use?

以下代码摘录:

public class OnFailureListener extends TestListenerAdapter {    

@Override   
public void onTestFailure(ITestResult tr) {     
   Screenshots.captureScreenshot(tr);

   super.onTestFailure(tr);             
}

-

public static void captureScreenshot(ITestResult tr) {
   WebDriver driver = TestClass.driver;

   if (driver instanceof TakesScreenshot) {                                                                                                         
      String filename = "path/to/screenshot/file";

   try {
      File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      FileUtils.copyFile(scrFile, new File(filename));
   } catch (IOException e) { e.printStackTrace(); }
}

推荐答案

如果您创建可访问该驱动程序的基本测试类,则该驱动程序将始终是正确的驱动程序

If you create a base test class with access to the driver, then that driver will always be the correct driver

以下将实现这一目标;

The following will achieve this;

  1. 所有测试类都必须扩展一个简单的基本测试类;

public asbtract baseTestCase() {

private WebDriver driver;

public WebDriver getDriver() {
    return driver;
}

@BeforeMethod
public void createDriver() {
    driver=XXXXDriver();
}

@AfterMethod
public void tearDownDriver() {
    if (driver != null){
        try{
            driver.quit();
        }
        catch (WebDriverException e) {
            System.out.println("***** CAUGHT EXCEPTION IN DRIVER TEARDOWN *****");
            System.out.println(e);
        }
    }
}

  1. 在您的侦听器中,您需要访问基类:

public class ScreenshotListener extends TestListenerAdapter {

@Override
public void onTestFailure(ITestResult result){
    Object currentClass = result.getInstance();
    WebDriver webDriver = ((BaseTest) currentClass).getDriver();
    if (webDriver != null){
        File f = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
        //etc.
        }
    }
}

这篇关于使用TestNG运行并行测试时捕获WebDriver屏幕截图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆