import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.*; import java.io.File; import org.apache.commons.io.FileUtils; public class ScreenshotTest { WebDriver driver; @BeforeMethod public void setup() { driver = new ChromeDriver(); driver.get("https://example.com"); } @Test public void testTitle() throws Exception { try { Assert.assertEquals(driver.getTitle(), "Wrong Title"); } catch (AssertionError e) { File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(src, new File("failure.png")); throw e; } } @AfterMethod public void teardown() { driver.quit(); } }
The test asserts the page title against a wrong expected value, so it fails.
The catch block takes a screenshot and saves it as 'failure.png'. Then it rethrows the AssertionError, so the test fails.
No exceptions are thrown from FileUtils.copyFile because it is declared to throw Exception and the test method declares 'throws Exception'.
File screenshot = new File("error.png");To verify a file was created, we check if it exists using exists().
Option C correctly asserts the file exists.
Option C checks if file size is zero, which is not guaranteed.
Option C asserts the file is not a file, which is wrong.
Option C asserts the file object is null, which is false.
File src = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(src, new File("/invalid_path/failure.png"));IOException occurs if the destination path is invalid or not writable.
Option D correctly identifies this cause.
Option D is incorrect because the cast is valid.
Option D is incorrect; getScreenshotAs returns a valid file or throws exception.
Option D is incorrect; copyFile does not require a third argument.
ITestListener provides callbacks like onTestFailure where you can add screenshot logic.
ISuiteListener is for suite-level events, not individual tests.
IAnnotationTransformer is for modifying annotations.
IInvokedMethodListener is for method invocation events but less commonly used for failure handling.
Visual evidence from screenshots helps quickly identify what went wrong.
Options A, B, and D are incorrect because screenshots do not affect execution time, fix bugs, or prevent failures.