简体   繁体   中英

TestNG listeners, how to pass class name?

I have my listener override like this :

    @Override
    public void onTestFailure(ITestResult result) {
        System.out.println("Test: " + getTestMethodName(result) + " failure");
        String methodName=result.getName().toString().trim();
        String className = result.getClass().toString().trim();
        takeScreenShot(methodName, className);

    }

    public void takeScreenShot(String methodName, String className) {
    driver=className.getDriver();  //it wont work this way :(
    File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

            FileUtils.copyFile(scrFile, new File(methodName+".png"));

}

lets say my class is TestClass, and there is method getDriver that returns driver, but:

driver=className.getDriver();

how to pass this className variable ? i dont want to make separate listeners for each class, and String className is not WebDriver type

any ideas?

public void takeScreenShot(ITestResult itr) {
    YourClass currentClass = (YourClass) itr.getInstance();
    WebDriver driver = currentClass.getDriver();

    // ...

You can work on this, in your class you need to set driver attribute and then you can use this attribute in Listener class for Example

testClass.java

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

Listner.java

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

You can use above driver from any class now, the only thing is you need to set the driver attribute value in you test class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM