Selenium Test Automation Visual Testing

Visual Regression Testing Using Selenium AShot: A Step-by-Step Approach

The other part of ensuring the UI of an application remains consistent is to ensure that the application works. Visual changes, even minor ones made unintentionally, can have an impact on the user experience and brand identity. Selenium, as a popular browser automation framework, combined with AShot, makes it easy to perform visual testing by capturing screenshots and comparing them.

This blog posts how to set up visual tests using Selenium AShot. I will discuss how one can take screenshots of the full page and an element-specific, as well as capture baseline images and update it with UI changes to detect changes where least expected.

Additionally, we’ll discuss how to fine-tune comparisons using AShot’s image comparison techniques, such as tolerance levels, ignored areas, and pixel-diff configurations. By the end, you’ll be equipped with the knowledge to integrate visual testing into your Selenium workflow, ensuring UI consistency across different builds and releases.

Table of Content

What is Visual Testing?

Visual Testing is a method of validating a web or mobile application’s user interface (UI) appearance by comparing visual elements between different versions or test runs. Unlike functional testing, which verifies if the system behaves as expected, visual testing ensures that the UI looks correct and detects unintended changes caused by CSS updates, layout shifts, or UI regressions.

Key Aspects of Visual Testing:

  • Detecting pixel-level differences between UI states
  • Validating color, font, alignment, and spacing
  • Ensuring responsive design works across different screen sizes
  • Comparing baseline images vs. new UI screenshots

Why is Visual Testing Important in UI Automation?

Traditional UI automation tests (e.g., Selenium) verify elements based on attributes like id, class, or text, but they do not check how the UI visually appears to end-users.

Benefits of Visual Testing:

  • Prevents UI Regressions: Detects unintended layout or styling changes.
  • Enhances User Experience: Ensures consistency across different browsers and devices.
  • Reduces Manual Effort: Replaces tedious manual visual checks with automation.
  • Works with Any UI Automation Framework: Can be integrated into Selenium, Cypress, Playwright, etc.
  • Validates Dynamic Content: Supports scrollable pages, popups, overlays, and animations.

Challenges of Traditional Functional Testing

Traditional automation frameworks (like Selenium, WebdriverIO, or Cypress) focus on verifying functionality but ignore UI appearance. This leads to issues such as:

  • Invisible Bugs: Tests might pass even if elements overlap, are cut off, or have incorrect colors.
  • Dynamic UI Elements: Visual changes due to different screen resolutions or browsers are hard to catch.
  • CSS Styling Changes: Minor updates in CSS (like padding/margin changes) might break UI but won’t fail functional tests.
  • Inconsistent Layouts: UI misalignment due to font, viewport size, or responsiveness can go unnoticed.

Example:
Imagine an e-commerce checkout button shifts slightly due to a CSS update.

  • Functional test: Passes because the button is still clickable.

Visual test: Fails because the button is misaligned or cut off.

Introduction to Selenium AShot

What is AShot?

AShot is an open-source Java library used for capturing, comparing, and processing screenshots in Selenium-based automation. Unlike Selenium’s built-in getScreenshotAs() method, which captures only the visible viewport, AShot can:

  • Capture full-page screenshots (including scrollable areas)
  • Take screenshots of specific elements instead of the entire page
  • Perform image comparison to detect UI changes
  • Handle dynamic content, ignored areas, and resizing.

Why Use AShot Over Selenium’s Default Screenshot Method?

FeatureSelenium getScreenshotAs()AShot
Full-page screenshotsNoYes
Element-specific screenshotsNoYes
Image comparisonNoYes
Scroll handlingNoYes
Ignore dynamic elementsNoYes

Example Use Case:

Imagine testing a website where a banner image updates dynamically. Selenium’s basic screenshot method won’t detect changes in that image. However, AShot can compare screenshots and highlight pixel-level differences.

How AShot Works for Image Comparison

AShot captures images using Selenium WebDriver and processes them through Java AWT (Abstract Window Toolkit). It enables pixel-by-pixel image comparison, making it highly effective for visual regression testing.

Steps of Image Comparison in AShot:

  1. Capturing Screenshots
    • AShot takes a screenshot of the entire page, a specific element, or a viewport.
    • Uses takeScreenshot(WebDriver driver) method.
    • Supports full-page scrolling screenshots (especially useful for long web pages).
  2. Processing and Normalization
    • Converts images into BufferedImage format.
    • Applies scaling, cropping, and transparency adjustments if required.
    • Can ignore anti-aliasing effects or minor UI shifts to reduce false positives.
  3. Performing Image Comparison
    • Compare the baseline image (expected UI state) with the newly captured screenshot.
    • Uses pixel-by-pixel matching with configurable tolerance levels.
    • Ignore specific areas (dynamic elements like timestamps, animations, etc.).
  4. Highlighting Differences
    • Generates an output image with highlighted differences (commonly in red).
    • Helps in debugging by clearly marking UI deviations.
  5. Reporting & Analysis
    • The difference percentage can be retrieved programmatically.
    • Can be integrated with reporting tools like ExtentReports for better visualization.

Key Features of AShot

  1. Full-page & element-based screenshots – AShot captures entire web pages or specific elements, including scrollable content, ensuring comprehensive UI verification.
  2. Image comparison with pixel-by-pixel diff detection – It performs an exact pixel comparison between baseline and new images, highlighting any UI changes.
  3. Ignore specific areas – AShot allows defining exclusion zones to skip dynamic elements like timestamps, ads, or animations, reducing false positives.
  4. Supports different screenshot strategies – Offers multiple capture modes, including viewport, full-page scrolling, cropping, and scaling, to match diverse testing needs.
  5. Compatible with TestNG & JUnit for seamless automation – Easily integrates with Java-based test frameworks, making it ideal for automated UI validation in Selenium projects.
  6. Lightweight & fast – Optimized for speed, AShot is efficient in CI/CD pipelines, ensuring quick feedback loops without adding significant test execution time.

Setting Up and Using AShot in Test Frameworks

Prerequisites (Java, Selenium, AShot Library)

Before integrating AShot, ensure that you have the following installed:

  • Java Development Kit (JDK) – Preferably JDK 8 or later.
  • Selenium WebDriver – Ensure Selenium 4+ is configured in your project.
  • Maven or Gradle – Dependency management tool for adding libraries.
  • TestNG or JUnit – AShot works seamlessly with both frameworks.

Installing and Configuring AShot in a Selenium Project

To use AShot in your project, follow these steps:

Add AShot Dependency:

If you’re using Maven, add the following AShot dependency in your pom.xml file:

<dependency>
    <groupId>ru.yandex.qatools.ashot</groupId>
    <artifactId>ashot</artifactId>
    <version>1.5.4</version>
</dependency>

For Gradle, add this in your build.gradle file:

dependencies {
    // Adding AShot library for capturing and comparing screenshots in tests
    implementation 'ru.yandex.qatools.ashot:ashot:1.5.4'
}

Import Required Packages

After adding the dependency, import the necessary classes in your Selenium test file:

import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.comparison.ImageDiff;
import ru.yandex.qatools.ashot.comparison.ImageDiffer;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;

/**
 * This class demonstrates how to take a screenshot using AShot and compare it with a baseline image.
 */

Set Up WebDriver and Capture Screenshots
Initialize WebDriver and capture a screenshot using AShot:

public class AShotExample {
    public static void main(String[] args) throws IOException {
        // Setup WebDriver
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com");

        // Capture Screenshot using AShot
        Screenshot screenshot = new AShot()
                .shootingStrategy(ShootingStrategies.viewportPasting(100)) // Handles full-page scrolling
                .takeScreenshot(driver);

        // Save the screenshot
        ImageIO.write(screenshot.getImage(), "PNG", new File("screenshot.png"));

        // Close the browser
        driver.quit();
    }
}

Key Takeaways:

  • Uses ShootingStrategies.viewportPasting(100) for capturing full-page screenshots.
  • Saves the captured image to a file in PNG format.
  • Uses Selenium WebDriver to navigate and take screenshots automatically.

Integrating AShot with TestNG or JUnit

To automate visual testing, we integrate AShot with TestNG or JUnit for assertion-based validation.

TestNG Integration Example:

import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.comparison.ImageDiff;
import ru.yandex.qatools.ashot.comparison.ImageDiffer;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class VisualTest {
    WebDriver driver;

    @BeforeClass
    public void setup() {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        driver = new ChromeDriver();
        driver.get("https://example.com");
    }

    @Test
    public void testVisualComparison() throws IOException {
        // Capture screenshot
        Screenshot actualScreenshot = new AShot()
                .shootingStrategy(ShootingStrategies.viewportPasting(100))
                .takeScreenshot(driver);

        // Load baseline image
        BufferedImage expectedImage = ImageIO.read(new File("baseline.png"));

        // Compare images
        ImageDiff diff = new ImageDiffer().makeDiff(new Screenshot(expectedImage), actualScreenshot);

        // Assert if images are different
        Assert.assertFalse(diff.hasDiff(), "Visual differences found!");
    }

    @AfterClass
    public void tearDown() {
        driver.quit();
    }
}

Key Takeaways:

  •  Use the TestNG @Test method for test execution.
  •  Captures actual screenshot dynamically and compares it with baseline.
  • Uses ImageDiff.hasDiff() for assertion-based validation.

Combining AShot with Selenium WebDriver Actions

AShot works well with Selenium WebDriver actions to handle specific UI elements.

Capturing a Specific Web Element

WebElement logo = driver.findElement(By.id("logo"));

Screenshot logoScreenshot = new AShot()
        .shootingStrategy(ShootingStrategies.simple()) // For single elements
        .takeScreenshot(driver, logo);

// Save the logo screenshot
ImageIO.write(logoScreenshot.getImage(), "PNG", new File("logo.png"));
  • Focuses on capturing only the selected WebElement.
  • Avoids unnecessary background UI details.

Key Notes for AShot Implementation:

  • Baseline Images Must Be Updated Regularly – If UI changes, update the expected images to prevent false failures.
  • Tolerance Levels Should Be Adjusted – Minor UI shifts can cause unwanted test failures; fine-tune the comparison parameters.
  • Use viewportPasting() for Full-page Captures – Ensures complete screenshots for pages with scrolling content.
  • Handle Dynamic Elements with Exclusions – Ignore areas with timestamps, ads, or animations to avoid inconsistent results.
  • Integrate with Test Frameworks (TestNG/JUnit) – Enables assertion-based testing for CI/CD automation.
  • Combine AShot with Reporting Tools (ExtentReports, Allure) – Provides detailed visual test reports.

Capturing Screenshots with AShot in Selenium

Full Page vs. Element Screenshots

  • Full-Page Screenshot

By default, Selenium’s getScreenshotAs() method captures only the visible part of the page. AShot overcomes this limitation by stitching multiple images together to capture the entire page.

Example: Capturing a Full-Page Screenshot

@Test
public void testFullPageScreenshot() {
    driver.get("https://magento.softwaretestingboard.com/");
    // Capture full page screenshot with scrolling
    Screenshot screenshot = new AShot()
            .shootingStrategy(ShootingStrategies.viewportPasting(1000))
            .takeScreenshot(driver);
    saveScreenshot(screenshot, "fullpage");
}

Explanation:

  • ShootingStrategies.viewportPasting(1000): Scrolls and captures the entire page with a delay of 1000ms.
  • The screenshot is saved using saveScreenshot()

Element-Specific Screenshot
Instead of capturing the entire page, you may need to capture specific UI components, such as buttons or forms.

Example: Capturing an Element Screenshot

@Test
public void testElementScreenshot() {
    driver.get("https://magento.softwaretestingboard.com/customer/account/login");
    WebElement element = driver.findElement(By.id("send2"));

    // Capture specific element screenshot
    Screenshot screenshot = new AShot()
            .coordsProvider(new WebDriverCoordsProvider())
            .takeScreenshot(driver, element);

    saveScreenshot(screenshot, "element");
}

Explanation:

  • coordsProvider(new WebDriverCoordsProvider()): Ensures accurate element cropping.
  • Useful for validating specific UI elements.

Handling Scrollable Pages

Some web pages load content dynamically when scrolled. AShot enables capturing such pages by scrolling and stitching images together.

Example: Capturing a Scrollable Page Screenshot

@Test
public void testScrollablePageScreenshot() {
    driver.get("https://magento.softwaretestingboard.com/");

    Screenshot screenshot = new AShot()
            .shootingStrategy(ShootingStrategies.viewportPasting(
                    ShootingStrategies.scaling(1.25f), 1000))
            .takeScreenshot(driver);

    saveScreenshot(screenshot, "scrollable");
}

Explanation:

  • viewportPasting(ShootingStrategies.scaling(1.25f), 1000): Adjusts scaling for better resolution while scrolling.
  • Helps test dynamically loaded content like infinite scrolls or large tables.

Handling Different Screen Resolutions

Web applications often have different layouts based on screen sizes (responsive design). AShot allows automated visual testing at multiple resolutions.

Example: Capturing Screenshots at Different Resolutions

@Test
public void testDifferentResolutions() {
    driver.get("https://magento.softwaretestingboard.com/");

    int[][] resolutions = {
            {1920, 1080},
            {1366, 768},
            {375, 812}  // iPhone X
    };

    for (int[] resolution : resolutions) {
        driver.manage().window().setSize(
                new org.openqa.selenium.Dimension(resolution[0], resolution[1])
        );

        Screenshot screenshot = new AShot()
                .shootingStrategy(ShootingStrategies.viewportPasting(1000))
                .takeScreenshot(driver);

        saveScreenshot(screenshot,
                String.format("resolution_%dx%d", resolution[0], resolution[1]));
    }
}

Explanation:

  • The script runs tests on different screen sizes (desktop, tablet, mobile).
  • Useful for testing responsiveness across various devices.

Custom Screenshot Strategies

For advanced cases, AShot allows custom configurations such as adjusting device pixel ratio (DPR) or handling headers/footers.

Example: Custom Screenshot Strategy

@Test
public void testCustomScreenshotStrategy() {
    driver.get("https://magento.softwaretestingboard.com/");

    Screenshot screenshot = new AShot()
            .shootingStrategy(ShootingStrategies.viewportPasting(
                    ShootingStrategies.scaling(2.0f), 1000))
            .coordsProvider(new WebDriverCoordsProvider())
            .takeScreenshot(driver);

    saveScreenshot(screenshot, "custom_strategy");
}

Explanation:

  • scaling(2.0f): Captures higher-resolution images for retina displays.
  • Can be combined with additional configurations like ignoring UI elements.

Saving Screenshots Automatically

The below method is responsible for saving captured images in a screenshots/ directory with a timestamp.

private void saveScreenshot(Screenshot screenshot, String name) {
    try {
        String timestamp = LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String fileName = String.format("screenshots/%s_%s.png", name, timestamp);
        ImageIO.write(screenshot.getImage(), "PNG", new File(fileName));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void saveScreenshot(BufferedImage image, String name) {
    try {
        String timestamp = LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String fileName = String.format("screenshots/%s_%s.png", name, timestamp);
        ImageIO.write(image, "PNG", new File(fileName));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Explanation:

  • Generates a timestamp-based filename.
  • Automatically saves all images in the screenshots/ directory.

Performing Image Comparison with AShot

Comparing Baseline vs. New Images

The first step in visual testing is to capture and store a baseline image. Then, we take a new screenshot in a subsequent test run and compare it with the baseline.

Example: Capturing and Comparing Screenshots

@Test
    public void testCompareScreenshots() {
        driver.get("https://magento.softwaretestingboard.com/");

        // Take baseline screenshot
        Screenshot baseline = ashot
                .shootingStrategy(ShootingStrategies.viewportPasting(1000))
                .takeScreenshot(driver);

        // Simulate some change in the page
        // ... make changes to the page ...

        // Take actual screenshot
        Screenshot actual = ashot
                .shootingStrategy(ShootingStrategies.viewportPasting(1000))
                .takeScreenshot(driver);

        // Compare screenshots
        ImageDiffer imageDiffer = new ImageDiffer();
        ImageDiff diff = imageDiffer.makeDiff(baseline, actual);

        // Assert and save difference if any
        if (diff.hasDiff()) {
            saveScreenshot(diff.getMarkedImage(), "difference");
            Assert.fail("Visual differences found in screenshots");
        }
    }

Explanation:

  • The first screenshot (baseline) serves as the expected image.
  • The second screenshot (newScreenshot) represents the actual state of the page.
  • ImageDiffer().makeDiff() compares the two images pixel by pixel.
  • If a difference is found, an image with highlighted differences is saved and the test fails.

Configuring Image Comparison Parameters (Tolerance, Ignoring Colors, etc.)

By default, AShot does pixel-perfect comparisons. However, in some cases, minor differences (such as anti-aliasing, color shifts, or dynamic content) can cause false failures. AShot allows you to configure tolerance levels and ignore specific areas or colors.

Example: Configuring Tolerance and Ignoring Colors

@Test
public void testImageComparisonWithTolerance() {
    driver.get("https://magento.softwaretestingboard.com/");

    // Capture baseline screenshot
    Screenshot baseline = new AShot()
            .shootingStrategy(ShootingStrategies.viewportPasting(1000))
            .takeScreenshot(driver);

    // Capture new screenshot
    Screenshot newScreenshot = new AShot()
            .shootingStrategy(ShootingStrategies.viewportPasting(1000))
            .takeScreenshot(driver);

    // Convert images to grayscale to reduce sensitivity to minor color variations
    BufferedImage baselineGray = convertToGrayscale(baseline.getImage());
    BufferedImage newScreenshotGray = convertToGrayscale(newScreenshot.getImage());

    // Perform image comparison with custom diff markup
    ImageDiff diff = new ImageDiffer()
            .makeDiff(new Screenshot(baselineGray), new Screenshot(newScreenshotGray));

    if (diff.hasDiff()) {
        saveScreenshot(diff.getMarkedImage(), "imageDifference_tolerance");
        Assert.fail("Visual differences found, but within allowed tolerance.");
    }
}

// Helper method to convert image to grayscale (reduces false positives due to color changes)
private BufferedImage convertToGrayscale(BufferedImage original) {
    BufferedImage grayscale = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
    grayscale.getGraphics().drawImage(original, 0, 0, null);
    return grayscale;
}

Explanation:

  • withColorTolerance(5): Allows minor color variations (useful for anti-aliasing).
  • withDiffMarkupPolicy(): Controls how differences are highlighted.
  • withIgnoredAreas(): (Optional) Lets you exclude specific parts of the screen.

Handling Minor UI Changes and Dynamic Content

Certain elements on web pages (e.g., timestamps, dynamic ads, user-generated content) change every test run. This can cause false positives in visual tests. AShot provides ways to ignore dynamic content.

Example: Ignoring Dynamic UI Elements

@Test
public void testImageComparisonWithIgnoredRegions() {
    driver.get("https://magento.softwaretestingboard.com/");

    // Capture baseline screenshot
    Screenshot baseline = new AShot()
            .shootingStrategy(ShootingStrategies.viewportPasting(1000))
            .takeScreenshot(driver);

    // Capture new screenshot
    Screenshot newScreenshot = new AShot()
            .shootingStrategy(ShootingStrategies.viewportPasting(1000))
            .takeScreenshot(driver);

    // Create copies of the images to manipulate
    BufferedImage baselineImg = deepCopy(baseline.getImage());
    BufferedImage newImg = deepCopy(newScreenshot.getImage());

    // Mask out header and footer on both images (making them identical in those regions)
    int width = baselineImg.getWidth();
    int height = baselineImg.getHeight();

    Graphics2D g1 = baselineImg.createGraphics();
    Graphics2D g2 = newImg.createGraphics();

    // Fill header and footer with the same color on both images
    g1.setColor(Color.WHITE);
    g2.setColor(Color.WHITE);

    // Header area (top 100px)
    g1.fillRect(0, 0, width, 100);
    g2.fillRect(0, 0, width, 100);

    // Footer area (bottom 100px)
    g1.fillRect(0, height - 100, width, 100);
    g2.fillRect(0, height - 100, width, 100);

    g1.dispose();
    g2.dispose();

    // Create new screenshots with masked images
    Screenshot maskedBaseline = new Screenshot(baselineImg);
    Screenshot maskedNewScreenshot = new Screenshot(newImg);

    // Compare the masked images
    ImageDiffer imageDiffer = new ImageDiffer();
    ImageDiff diff = imageDiffer.makeDiff(maskedBaseline, maskedNewScreenshot);

    if (diff.hasDiff()) {
        saveScreenshot(diff.getMarkedImage(), "imageDifference_maskedComparison");
        Assert.fail("Visual differences found outside ignored regions");
    }
}

Explanation:

  • ShootingStrategy(viewportPasting): Captures screenshots with a viewport-based strategy to ensure the entire page is included.
  • deepCopy(): Creates copies of the images to manipulate without affecting the original screenshots.
  • Graphics2D.fillRect(): Masks the header and footer areas by filling them with white, ignoring those regions during the comparison.

Handling Visual Differences and Debugging Failures in Visual Testing with AShot

Understanding Image Diff Outputs

When performing visual testing, image comparison tools generate diff outputs, highlighting discrepancies between the baseline (expected) and actual images. These differences are often represented using color overlays to show added, removed, or changed pixels.

  • Pixel-to-pixel comparison: Compares images at a pixel level. Even minor differences in rendering can trigger failures.
  • Perceptual comparison: Uses algorithms to detect noticeable differences while ignoring minor pixel shifts.
  • Threshold-based comparison: Allows tolerance levels to define acceptable variations.

Example:

If the application UI shifts slightly due to font rendering differences on different machines, pixel-to-pixel comparison might falsely detect changes. A perceptual comparison method would handle this more accurately.

Logging and Reporting Differences

Proper logging helps identify and troubleshoot failures. Key practices include:

  • Logging before and after screenshots for failed cases.
  • Attaching diff images to test reports for quick debugging.
  • Using test automation tools like ExtentReports to capture and embed these differences.

Example:

In Selenium, you can save screenshots of expected vs. actual UI states and log them using the AShot library combined with ExtentReports.

Strategies to Reduce False Positives in Visual Testing

False positives occur when minor, acceptable changes (e.g., anti-aliasing, minor layout shifts) trigger failures. To mitigate these:

  • Set a comparison threshold: Adjust sensitivity levels to ignore minor variations.
  • Ignore dynamic elements: Mask areas with timestamps, animations, or dynamic content.
  • Use a stable testing environment: Ensure consistent screen resolution, browser settings, and OS versions.

Integrating ExtentReports for Enhanced Reporting

Overview of ExtentReports

ExtentReports is a popular reporting library in Selenium that provides interactive and structured test reports. It allows:

  • Detailed step-by-step logging with screenshots.
  • Categorization of test results (pass, fail, skip).
  • Easy embedding of images and diff results for visual testing.

Setting Up ExtentReports in a Project

To integrate ExtentReports with Selenium and AShot:

  1. Add the ExtentReports dependency in your project (Maven/Gradle).
  2. Initialize ExtentReports in your test setup.
  3. Capture and attach screenshots in case of test failures.
  4. Generate an HTML report with visual diffs.

Example (Java + Selenium + AShot + ExtentReports)

ExtentTest test = extent.createTest("Visual Test");
Screenshot screenshot = new AShot().takeScreenshot(driver);
ImageIO.write(screenshot.getImage(), "PNG", new File("actual.png"));

test.fail("Visual differences found")
    .addScreenCaptureFromPath("actual.png");

Capturing and Embedding Screenshots with AShot

AShot simplifies screenshot capture by allowing:

  • Full-page, element-specific, and viewport-based screenshots.
  • High-quality image comparison with various strategies.

Example: Capturing an element’s screenshot

WebElement element = driver.findElement(By.id("logo"));
Screenshot screenshot = new AShot().takeScreenshot(driver, element);
ImageIO.write(screenshot.getImage(), "PNG", new File("logo.png"));

Generating Interactive and Visual Reports

ExtentReports allows embedding images directly into the test report. The workflow involves:

  • Capturing before/after images.
  • Comparing them and generating a diff image.
  • Attaching images to the report for easy debugging.

Example:

test.fail("Mismatch found")
    .addScreenCaptureFromPath("diff.png");

Best Practices for Visual Testing with AShot

When to Use Visual Testing in Automation

Visual testing should be used in scenarios where UI accuracy is critical, such as:

  • Verifying page layouts after UI updates.
  • Checking for unintended UI regressions.
  • Testing responsive designs across different screen sizes.

Maintaining and Updating Baseline Images

Regular maintenance of baseline images is crucial to avoid unnecessary failures. Best practices include:

  • Updating baseline images only after verifying UI changes.
  • Storing baseline images in a version control system (e.g., Git).
  • Running visual tests in consistent environments to reduce discrepancies.

Avoiding Common Mistakes in Visual Regression Testing

To ensure reliable visual tests, avoid:

  • Overly strict comparisons: Set appropriate thresholds to ignore minor rendering differences.
  • Testing dynamic elements without masking: Exclude sections like timestamps, carousels, or animations.
  • Skipping environment consistency checks: Differences in OS, browser versions, and screen resolutions can cause false failures.

Conclusion

Visual testing with Selenium AShot enhances UI validation by detecting unintended visual regressions. By integrating ExtentReports, teams can generate detailed reports with image comparisons, making debugging easier. Following best practices like threshold-based comparison, baseline image management, and dynamic element masking ensures stable and reliable visual test automation.

Witness how our meticulous approach and cutting-edge solutions elevated quality and performance to new heights. Begin your journey into the world of software testing excellence. To know more refer to Tools & Technologies & QA Services.

If you would like to learn more about the awesome services we provide,  be sure to reach out.

Happy Testing 🙂