Taking a screenshot when a test fails helps you see what went wrong. It shows the exact screen state at failure.
Screenshot attachment on failure in Selenium Java
try { // test steps } catch (Exception e) { File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("path/to/save/screenshot.png")); throw e; // rethrow to mark test as failed }
Use TakesScreenshot interface from Selenium to capture the screen.
Save the screenshot file to a known folder for easy access.
failure.png in the screenshots folder.File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshots/failure.png"));try { // some test code } catch (Exception e) { File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("screenshots/error_" + System.currentTimeMillis() + ".png")); throw e; }
This test opens a website, tries to find a missing element to cause failure, then takes a screenshot and saves it. It prints messages about the screenshot and failure.
import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.apache.commons.io.FileUtils; import java.io.File; public class ScreenshotOnFailureTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com"); // Intentionally fail: find element that does not exist driver.findElement(By.id("nonexistent-element")); } catch (Exception e) { try { File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("screenshots/failure.png")); System.out.println("Screenshot saved on failure."); } catch (Exception ioException) { System.out.println("Failed to save screenshot: " + ioException.getMessage()); } System.out.println("Test failed: " + e.getMessage()); } finally { driver.quit(); } } }
Make sure the screenshots folder exists or create it before saving files.
Use meaningful file names or timestamps to avoid overwriting screenshots.
Integrate screenshot capture in test frameworks like JUnit or TestNG listeners for automatic capture on failure.
Taking screenshots on failure helps you see what went wrong visually.
Use Selenium's TakesScreenshot interface to capture and save images.
Save screenshots with clear names and handle exceptions during saving.