0
0
Selenium Javatesting~15 mins

Screenshot attachment on failure in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Capture screenshot when test fails
Preconditions (3)
Step 1: Open the browser and navigate to 'https://example.com/login'
Step 2: Enter 'wronguser' in the username field
Step 3: Enter 'wrongpass' in the password field
Step 4: Click the login button
Step 5: Verify that the login failed by checking the error message is displayed
Step 6: If the verification fails, capture a screenshot and save it to 'screenshots' folder
✅ Expected Result: On test failure, a screenshot image file is saved with a timestamped filename in the 'screenshots' folder
Automation Requirements - TestNG with Selenium WebDriver
Assertions Needed:
Assert that the error message element is displayed after login attempt
Best Practices:
Use @AfterMethod to capture screenshot on failure
Use explicit waits to wait for elements
Use descriptive file names with timestamps for screenshots
Use Page Object Model for element locators (optional but recommended)
Automated Solution
Selenium Java
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.

Common Mistakes - 4 Pitfalls
Not using explicit waits before interacting with elements
Taking screenshot only inside the test method
Hardcoding screenshot file paths without creating directories
Using fixed screenshot file names
Bonus Challenge

Now add data-driven testing with 3 different invalid username and password combinations

Show Hint