gpt4 book ai didi

java - 如何在 ItestListener 中获取当前的类驱动程序

转载 作者:行者123 更新时间:2023-11-30 02:10:12 25 4
gpt4 key购买 nike

我正在为我的 testng-selenium-java 项目使用 ExtentReports 和 ItestListener,我的监听器截取了 ExtentReports 失败测试用例的屏幕截图,但问题是我的 testng.XML 中有多个类,我一次运行它们,一个接一个地执行不同的操作并拥有自己的驱动程序。

在失败的情况下,Ilistener 的代码是 -

public void onTestFailure(ITestResult iTestResult) 
{
System.out.println("I am in onTestFailure method " +
getTestMethodName(iTestResult) + " failed");

//Get driver from BaseTest and assign to local webdriver variable.
Object testClass = iTestResult.getInstance();
WebDriver webDriver = ((BaseTest) testClass).getDriver();


//Take base64Screenshot screenshot.
String base64Screenshot = "data:image/png;base64,"+((TakesScreenshot)webDriver).
getScreenshotAs(OutputType.BASE64);

//Extentreports log and screenshot operations for failed tests.
ExtentTestManager.getTest().log(LogStatus.FAIL,"Test Failed",
ExtentTestManager.getTest().addBase64ScreenShot(base64Screenshot));
}

如何确保每当测试用例失败时都会采用失败测试用例所在类的驱动程序,因为在上面的代码中始终只给出一个类的驱动程序,而不是当前类的驱动程序。

最佳答案

很简单,您可以在测试类中设置该属性,然后在监听器类中调用该属性

例如

testClass.java

@BeforeClass
public void setDriver(ITestContext context){
Webdriver driver = new FirefoxDriver();
context.setAttribute("WebDriver", driver);
}
@Test
public void t1(){
// your code
}

监听器.java

WebDriver driver = null;
@Override
public void onTestFailure(ITestResult result) {
ITestContext context = result.getTestContext();
driver = (WebDriver) context.getAttribute("WebDriver");
// your code
}

这里您需要注意,在您的测试类中您需要设置驱动程序属性,然后在该监听器中调用该属性一次。您的测试类和监听器类中的驱动程序将是相同的

关于java - 如何在 ItestListener 中获取当前的类驱动程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50347922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com