TestNG (Part 2)
How to take Screenshots only on Test Failure?
Here are the steps to capture a screenshot in selenium in this case:
- Create a class. Implement TestNG ‘ITestListener‘.
- Call the method ‘onTestFailure’.
- Add the code to take a screenshot with this method.
- Get the Test method name and take a screenshot with the test name.
- Then place it in the desired destination folder.
public class TestListener implements ITestListener {
WebDriver driver=null;
String filePath = "D:\\SCREENSHOTS";
@Override
public void onTestFailure(ITestResult result) {
System.out.println("***** Error "+result.getName()+" test has failed **");
String methodName=result.getName().toString().trim();
ITestContext context = result.getTestContext();
WebDriver driver = (WebDriver)context.getAttribute("driver");
takeScreenShot(methodName, driver);
}