10

I have a testcase that will invoke the driver as a non static variable. I also have added screenshot listener in my test case. When the test case fails The control is automatically sent to the screenshot listener... however since my driver is a NON-STATIC variable it could not be accessed in the screenshot listener. So I get nullpointer exception.

Is there a way to globally access the non-static driver in the screenshot listener?

My test case :

@Test
public void testCase() {
     //non-static driver is initialized
}

My screenshot listener :

public class ScreenshotListener extends TestListenerAdapter
{
    @Override
    public void onTestFailure(ITestResult testResult) {
        //driver needs to be accessed here
    }
}
0

5 Answers 5

19

YOu do not have to pass the driver around or call on testfailure within the test (infact this defeats the point of test listeners);

The following will achieve screenshots in listeners without passing the driver around;

  1. 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);
                    }
    
            }
        }
    
  2. 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.
        }
}

Your test is now unaware that a screenshgot is even being captured and can be controlled by the adding of the listener.

3
  • 1
    Thanks Dude ! Only difference your option of typecasting into base class and using Guide Inject lib with text context is, your option works for parallel execution where as other does not. Thanks again ! Jan 25, 2017 at 7:45
  • This really helped me as well, I spent days to get rid of this NPE.
    – Eajaz
    Jan 1, 2019 at 2:57
  • 1
    even after almost 10 years from this answer, this was a perfect and easy solution!
    – sayhan
    Feb 17, 2023 at 9:53
4

I was going to go for the solution provided by Robbie but wanted to avoid tying up my base class. As i was using to Guice to inject my WebDriver provider i opted to pass the instance through a TestNG attribute by hooking it up once in a setup test class like so:

public class Setup {
    @Inject WebDriver driver;

    @BeforeSuite
    public void onStart(ITestContext testContext) {
        testContext.setAttribute("WebDriver", this.driver);
    }
}

Then in my listener i simply pull it out:

@Override
public void onTestFailure(ITestResult result) {

    Object webDriverAttribute = 
        result.getTestContext().getAttribute("WebDriver");
    // test, cast, and use...

Was hoping for a better way that did not require casting but yet to find one.

-1

If you want to access driver everywhere in project then define wedDriver like below in browser setup class like

public class BrowserSetup{
private WebDriver driver;
public WebDriver getDriver() 
{
    return driver;
}
     use rest of code 
}

And use following code in testng listener

public class TestNgListener extends BrowserSetup implements ITestListener, ISuiteListener, IInvokedMethodListener{
WebDriver driver =null;

@Override
public void onTestFailure(ITestResult arg0) {
    Object currentClass = arg0.getInstance();
    WebDriver driver = ((BrowserSetup) currentClass).getDriver();
    //this.driver = ((BrowserSetup)currentClass).getDriver;

    // This is calling the printTestResults method
    try {
        getScreenshot(arg0.getTestName(), driver);
        System.out.println("Screenshot taken");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        System.out.println("Exception while takescreenshot "+e.getMessage());
        //e.printStackTrace();
    }
    printTestResults(arg0);

}
-1

You can also do this without listeners. In your base test class, add the below code in @afterTest (or any of the @afterXXXX annotation based on your requirement.)

@AfterMethod
public void afterMethod(ITestResult result){
    try {
        if (result.getStatus() == ITestResult.FAILURE) {
            //add your screenshot logic here.
        } else if (result.getStatus() == ITestResult.SKIP) {

        } else if (result.getStatus() == ITestResult.SUCCESS){

        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {

    }
-3

If you what to access your driver anywhere means, you have to pass your driver reference as an argument to everywhere as your execution flow goes,

// i assume onTestFailure method has been called explicitly.

@Test
public void testCase() 
{
  Webdriver driver=XXXXDriver();
  try
  {
       // your tests
  }
  catch(Exception e)
  {
      onTestFailure(new ITestResult (),driver)
  }

public class ScreenshotListener extends TestListenerAdapter
{

   @Override
   public void onTestFailure(ITestResult testResult,Webdriver driver) 
   {
      // you can access your driver here
   }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.