Search code examples
javaselenium-webdriverautomated-teststestnglistener

How to refer to the Webdriver object in selenium without making it static to take screenshot through Testng listeners on Test Failure


Hi Im stuck in a situation where I have declared my driver object in the test class and I have some wrappers developed in another class , all the respective variables are not static including the driver object , so now I want to take a screenshot on failure using testng listerners (I have created a custom listener class implementing to ITestListener) and when I refer to the driver object it throws a null exception probably due to driver not been static , how can I still achieve to take a screenshot without making the driver static , any testng related work around will also be helpful

this is the code line in my custom listenerclass

onTestFailure(){
    bufferImage = driver.getScreenshot(); //throws null , getScreesnshot comes from my wrapper class
}

I want to take the screenshot on test failure using testng listeners , without making the driver object static


Solution

  • You can put your driver object to test context and then take if from test context in onFailure method. Here is short example where everython is in single class but it would be working just fine in multi-class case as well:

    @Listeners({TestL.class})
    public class TestL implements ITestListener {
    
        
        
        @BeforeTest
        public void setUp(ITestContext context){
            WebDriver driver = new ChromeDriver();
            // Put object to context
            context.setAttribute("myDriver", driver);
        }
    
        @Test
        public void toFail(){
            Assert.fail();
        }
    
        @Override
        public void onTestFailure(ITestResult result) {
            System.out.println("Test failed..");
            // Take object from context and do some actions
            File screenShot = ((TakesScreenshot)result
                    .getTestContext()
                    .getAttribute("myDriver")).getScreenshotAs(OutputType.FILE);
        }
    }
    

    Do not forget to quit your session appropriately.