'How to move failed testcase code from @Aftermethod to TESTNG Listener?
This is the working code to capture screenshot for failure testcases in Extent reports I am trying to put inside TESTNG listeners:
@AfterMethod
public void tearDown(ItestResult result){
if(result.getStatus()==ItestResult.FAILURE){
extentTest.log(LogStatus.FAIL,"TEST CASE FAILED IS "+result.getName());
extentTest.log(LogStatus.FAIL, "TEST CASE FAILED IS "+result.getThrowable();
String screenshotPath = FreeCRMTest.getScreenshot(driver, result.getName());
extentTest.log(LogStatus.FAIL, extentTest.addScreeCapture(screenshotPath));
}
}
This is code to capture screenshot which I placed in base class:
public class base{
public WebDriver driver;
public WebDriver initializeDriver()
{
Properties prop=new Properties();
FileInputStream fis=new FileInputStream("path of data.properties");
prop.load(fis);
String browserName=prop.getProperty("browser");
if(browserName.equals("chrome"))
{
System.setProperty("webdriver.chrome.driver", "E:\Selenium Grid\chromedriver.exe");
driver=new ChromeDriver();
}
else if (browserName.equals("firefox"))
{
System.setProperty("webdriver.gecko.driver", "E:\Selenium Grid\ geckodriver.exe");
driver=new FirefoxDriver();
}
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));
return driver;
}
}
public static String getScreenshot(WebDriver driver, String screenshotName) throw IOException{
String dateName = new SimpleDateFormat("yyyyMMddhhmmss").fomat(new Date());
TakesScreenshot ts = (TakesScreenshot)driver;
File source=ts.getScreenshotAs(OutputType.File);
String destination=System.getProperty("user.dir")+"/FailedTestsScreenshots/" + screenshotName+dateName+ ".png";
File finalDestination = new File(destination);
FileUtils.copyFile(source, Final Destination);
return destination;
}
This is how I moving my code from @Aftermethod to TESTNG listener but it's throwing driver is null:
ExtentTest test;
public void onTestFailure(ItestFailure) {
test.log(STATUS.FAIL, result.getThrowable());
try{
String screenshotPath;
screenshotPath=getScreenshot(driver, result.getName());
test.log(STATUS.FAIL, test.addScreenCapture(screenshotPath));
}catch(IOException e) {
e.printStackTrace();
}
}
This is the maintest case which calls OnTestFailure:
public class Homepage extends Resources.base{
@Test
public void basePageNavigation()
{
driver=initializeDriver();
driver.get("http://www.google.com");
Assert.assertTrue("Google1", driver.gettitle() );
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
