Open In App

Cross-Browser Testing Using Selenium WebDriver

Last Updated : 31 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Selenium is an open-source framework that automates browser interactions, making it ideal for cross-browser testing. Cross-browser testing verifies that a web application functions consistently across multiple browsers like Chrome, Firefox, Safari, Edge, and programming languages include Java, Python, JavaScript, etc.

Cross-browser testing is important because users access web applications through various browsers. If a website looks or functions not properly on certain browsers, it risks losing potential customers.

Here are the steps to implementing cross-browser testing with Selenium:

Step 1. Set Up Your Environment.

Set up Selenium WebDriver, download the appropriate browser driver (e.g., ChromeDriver or GeckoDriver), and set it up in your project. Use a testing framework like TestNG or JUnit to organize and run tests.

Step 2. Create a Maven project.

Add the required libraries of Selenium and testNG to the pom.xml.

XML
<dependencies>
  		<dependency>
			<groupId>org.seleniumhq.selenium</groupId>
			<artifactId>selenium-java</artifactId>
			<version>4.13.0</version>
		</dependency>
		
		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>7.4.0</version>
		</dependency>
</dependencies>

Create the Class of java which name CrossBrowserTest.java.

Java
package ActionsTest;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class CrossBrowserTest {

    private WebDriver driver;

    @Test(dataProvider = "getBrowserData")
    public void testLoginFunctionality(String browser) {
        // Initialize WebDriver based on the browser
        initializeDriver(browser);

        try {
            // Navigate to SauceDemo login page
            driver.get("https://www.saucedemo.com/");

            // Validate page title
            Assert.assertTrue(driver.getTitle().contains("Swag Labs"), 
                "Page title does not contain 'Swag Labs' on " + browser);

            // Perform login
            WebElement usernameField = driver.findElement(By.id("user-name"));
            WebElement passwordField = driver.findElement(By.id("password"));
            WebElement loginButton = driver.findElement(By.id("login-button"));

            usernameField.sendKeys("standard_user");
            passwordField.sendKeys("secret_sauce");
            loginButton.click();

            // Wait for page load (implicit wait could be set globally)
            try {
                Thread.sleep(2000); // Simple wait; replace with explicit wait in production
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // Validate successful login by checking for inventory page
            WebElement inventoryContainer = driver.findElement(By.className("inventory_list"));
            Assert.assertTrue(inventoryContainer.isDisplayed(), 
                "Login failed: Inventory list not displayed on " + browser);

            // Validate URL after login
            Assert.assertTrue(driver.getCurrentUrl().contains("inventory.html"), 
                "URL does not indicate successful login on " + browser);

            System.out.println("Test passed on " + browser + ": Login functionality works.");
        } catch (Exception e) {
            System.err.println("Test failed on " + browser + ": " + e.getMessage());
            Assert.fail("Test failed on " + browser + ": " + e.getMessage());
        }
    }

    public void initializeDriver(String browser) {
        if (browser.equalsIgnoreCase("chrome")) {
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--start-maximized");
            // Optional: Add headless mode for CI/CD
            // options.addArguments("--headless");
            driver = new ChromeDriver(options);
        } else if (browser.equalsIgnoreCase("firefox")) {
            FirefoxOptions options = new FirefoxOptions();
            // Optional: Add headless mode
            // options.addArguments("--headless");
            driver = new FirefoxDriver(options);
        } else {
            throw new IllegalArgumentException("Unsupported browser: " + browser);
        }

        // Maximize window (optional, as ChromeOptions can handle this)
        driver.manage().window().maximize();
    }

    @DataProvider
    public Object[][] getBrowserData() {
        return new Object[][] {
            {"chrome"},
            {"firefox"}
        };
    }

    @AfterMethod
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}

Here we did:

  • Cross-browser testing with Selenium WebDriver and TestNG.
  • DataProvider is used to run the test on multiple browsers (Chrome and Firefox).
  • WebDriver is initialized based on the selected browser (Chrome or Firefox).
  • Navigates to SauceDemo login page and verifies the page title.
  • Performs a login action with predefined credentials.
  • Checks for the presence of the inventory list to confirm successful login.
  • Validates the page title and URL to ensure the login is successful.
  • Closes the browser after the test execution.

Output:

CrossBrowserTest-output
Cross Browser Test output

Cross-browser testing strategy verify consistent functionality of the application across different web browsers. By using Selenium WebDriver with TestNG and the DataProvider feature, we can easily execute the same test on multiple browsers like Chrome and Firefox, which make sure that the application's features work as expected.


Article Tags :

Similar Reads