Screenshot attachment on failure in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.ITestResult; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class LoginTest { private WebDriver driver; private WebDriverWait wait; @BeforeMethod public void setUp() { driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.manage().window().maximize(); } @Test public void testInvalidLoginShowsError() { driver.get("https://example.com/login"); WebElement usernameInput = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username"))); usernameInput.sendKeys("wronguser"); WebElement passwordInput = driver.findElement(By.id("password")); passwordInput.sendKeys("wrongpass"); WebElement loginButton = driver.findElement(By.id("loginBtn")); loginButton.click(); WebElement errorMsg = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("error-message"))); Assert.assertTrue(errorMsg.isDisplayed(), "Error message should be displayed on invalid login"); } @AfterMethod public void tearDown(ITestResult result) { if (ITestResult.FAILURE == result.getStatus()) { takeScreenshot(result.getName()); } if (driver != null) { driver.quit(); } } private void takeScreenshot(String testName) { try { File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")); Path destPath = Path.of("screenshots", testName + "_" + timestamp + ".png"); Files.createDirectories(destPath.getParent()); Files.copy(srcFile.toPath(), destPath, StandardCopyOption.REPLACE_EXISTING); System.out.println("Screenshot saved to: " + destPath.toAbsolutePath()); } catch (IOException e) { System.err.println("Failed to save screenshot: " + e.getMessage()); } } }
This test class uses Selenium WebDriver with TestNG to automate a login failure scenario.
setUp() initializes the Chrome browser and sets an explicit wait.
testInvalidLoginShowsError() opens the login page, enters wrong credentials, clicks login, and asserts the error message is visible.
tearDown() runs after each test. If the test failed, it calls takeScreenshot() to capture the browser screen and save it with a timestamped filename in the screenshots folder. Then it closes the browser.
takeScreenshot() uses Selenium's TakesScreenshot interface to get the screenshot file, creates the folder if needed, and saves the file with a name that includes the test method name and current time. This helps identify which test failed and when.
This approach ensures that any failure during the test run is documented visually, helping debugging.
Now add data-driven testing with 3 different invalid username and password combinations