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.
Practice
Solution
Step 1: Understand the role of screenshots in testing
Screenshots help testers see what the application looked like when a test failed.Step 2: Identify the benefit of visual evidence
This visual evidence helps diagnose issues faster and more clearly than logs alone.Final Answer:
To visually capture the state of the application at failure -> Option CQuick Check:
Screenshot = Visual failure evidence [OK]
- Thinking screenshots fix errors automatically
- Believing screenshots speed up tests
- Assuming screenshots reduce report size
Solution
Step 1: Recall Selenium interfaces for screenshots
TheTakesScreenshotinterface provides the method to capture screenshots.Step 2: Differentiate from other interfaces
Other interfaces likeWebDrivercontrol browser,Alerthandles popups, andJavascriptExecutorruns JS scripts.Final Answer:
TakesScreenshot -> Option DQuick Check:
TakesScreenshot = Capture screenshots [OK]
- Using WebDriver directly for screenshots
- Confusing Alert or JavascriptExecutor with screenshot capture
- Not casting driver to TakesScreenshot
File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File("screenshots/fail.png"));Solution
Step 1: Analyze the screenshot capture code
The driver is cast toTakesScreenshotand screenshot saved as a file named "fail.png" in the "screenshots" folder.Step 2: Check for errors or randomness
FileUtils.copyFile copies the screenshot correctly; file name is fixed as "fail.png" so no randomness.Final Answer:
Screenshot saved as fail.png in screenshots folder -> Option BQuick Check:
Code saves fixed-name screenshot file [OK]
- Forgetting to cast driver to TakesScreenshot
- Not importing or defining FileUtils
- Expecting random file names without code for it
File srcFile = driver.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File("screenshots/error.png"));Solution
Step 1: Check method call on driver
ThegetScreenshotAsmethod belongs toTakesScreenshot, so driver must be cast before calling it.Step 2: Verify other parts
FileUtils.copyFile exists and OutputType.FILE is correct. Relative paths are allowed if folder exists.Final Answer:
driver must be cast to TakesScreenshot before calling getScreenshotAs -> Option AQuick Check:
Cast driver to TakesScreenshot before screenshot [OK]
- Calling getScreenshotAs directly on WebDriver
- Assuming OutputType.FILE is wrong
- Thinking relative paths cause errors
@AfterMethod
public void tearDown(ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File dest = new File("screenshots/" + result.getName() + ".png");
FileUtils.copyFile(src, dest);
// Attach dest to report here
}
driver.quit();
}Solution
Step 1: Check condition for failure
The code checks if test status is FAILURE before taking screenshot, so it runs only on failures.Step 2: Verify screenshot saving and naming
Screenshot saved with test method name, which is valid. Attaching to report is indicated as a comment.Step 3: Confirm no errors in logic
FileUtils.copyFile may throw IOException but typically handled or declared; this snippet focuses on logic correctness.Final Answer:
This code saves screenshot only on failure and attaches it correctly -> Option AQuick Check:
Screenshot on failure only with correct naming [OK]
- Taking screenshots regardless of test result
- Not handling exceptions from file operations
- Assuming getName() returns null
Ready to prove it?
Pass the test and this pattern moves unknown
