1 min read

TestNG (Part 2)

TestNG
TestNG

How to take Screenshots only on Test Failure?

Here are the steps to capture a screenshot in selenium in this case:

  1. Create a class. Implement TestNG ‘ITestListener‘.
  2. Call the method ‘onTestFailure’.
  3. Add the code to take a screenshot with this method.
  4. Get the Test method name and take a screenshot with the test name.
  5. 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);
    }

Reference