Non Static driver and screenshot listener in TestNG
java, selenium, selenium-webdriver, testng
Solution
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;
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.
}
}
Your test is now unaware that a screenshgot is even being captured and can be controlled by the adding of the listener.
Problem
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 } } ```