In my previous post ( "Road to capture screen shot of failed webdriver test script part1") I have posted how to capture screen shot using exception handling, but in this post I will show you how to capture screen shot by overriding testng listeners.
Here is code (MyListner.java) where I override onTestFailure, onTestSuccess and onTestSkipped methods of class TestListenerAdapter. Created function CaptureScreenShot and called it into onTestFailure function.
I called above created listeners java file in below “FailedTestScreenCapture.java” TestNg file.
Here is code (MyListner.java) where I override onTestFailure, onTestSuccess and onTestSkipped methods of class TestListenerAdapter. Created function CaptureScreenShot and called it into onTestFailure function.
package
com.webdriver.test;
import
java.io.File;
import
java.io.IOException;
import
org.apache.commons.io.FileUtils;
import
org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import
org.openqa.selenium.WebDriver;
import
org.testng.ITestResult;
import
org.testng.TestListenerAdapter;
public class
MyListner extends TestListenerAdapter{
@Override
public void
onTestFailure(ITestResult result){
CaptureScreenShot(result);
System.out.println(result.getName()+" Test Failed \n");
}
@Override
public void
onTestSuccess(ITestResult result){
System.out.println(result.getName()+"
Test Passed \n");
}
@Override
public void
onTestSkipped(ITestResult result){
System.out.println(result.getName()+" Test Skipped \n");
}
public void
CaptureScreenShot(ITestResult result){
Object obj = result.getInstance();
WebDriver driver =
((FailedTestScreenCapture) obj).getDriver();
File scrFile = ((TakesScreenshot)
driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile, new File(“screenshot/”
result.getName()+".png"));
}
catch (IOException e) {
e.printStackTrace();
}
}
}
I called above created listeners java file in below “FailedTestScreenCapture.java” TestNg file.