Can you explain how you would take screenshots for a failing test on selenium?

Step 1: Implement Screenshot Logic

Create a utility method that captures screenshots. This method will take the WebDriver instance and the file name as parameters and use the TakesScreenshot interface provided by Selenium.


import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import java.io.File;
import org.apache.commons.io.FileUtils;
public class Utility {
    public static void captureScreenshot(WebDriver driver, String screenshotName) {
        try {
            TakesScreenshot ts = (TakesScreenshot) driver;
            File source = ts.getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(source, new File(“./Screenshots/” + screenshotName + “.png”));
            System.out.println(“Screenshot taken”);
        } catch (Exception e) {
            System.out.println("Exception while taking screenshot: " + e.getMessage());
        }
    }
}

Step 2: Integrate Screenshot Logic with TestNG Listeners

Use TestNG listeners to trigger screenshot capture upon test failure. Implement ITestListener to customize the behavior when a test fails.


import org.openqa.selenium.WebDriver;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class TestListener implements ITestListener {
    @Override
    public void onTestFailure(ITestResult result) {
       // Assuming WebDriver instance is stored or accessible from the test
       Object testClass = result.getInstance();
       WebDriver driver = ((YourTestClass) testClass).getDriver();

Utility.captureScreenshot(driver, result.getName());
}


}  

Replace YourTestClass with the actual class name of your test, and ensure you have a method getDriver() in your test class that returns the WebDriver instance.

Step 3: Configure TestNG to Use the Listener

You can annotate your test class with @Listeners to specify that TestNG should use your custom listener.


import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners(TestListener.class)
public class YourTestClass {
    private WebDriver driver;
    // Test methods here
    public WebDriver getDriver() {
       return driver;
    }
}