Webdriver take screen shot when case failed use TestNG

本文介绍了一种在方法级别并行运行测试时捕获截图的方法。通过为每个测试创建唯一的WebDriver实例,确保了截图与正确的测试相关联。文章提供了一个基类的示例代码,并展示如何在测试失败时获取当前类的WebDriver实例来捕获截图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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?


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;

All test classes must extend a simple base test class;


public asbtract baseTestCase() {

    private WebDriver driver;

    public WebDriver getDriver() {
            return driver;
}

    @BeforeMethod
    public void createDriver() {
            Webdriver 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);
                }

        }
    }

In your listener, you need to access the base class;

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.
        }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值