Selenium GRID

Prashant DhotrePrashant Dhotre
2 min read

What is Selenium Grid?
Selenium Grid is a tool that enables you to run Selenium tests simultaneously on multiple machines, operating systems, and browsers. It allows you to run tests in parallel across various environments.
It consists of:

  • Hub: The central point that receives test requests and directs them to nodes.

  • Nodes: Machines (or containers) where browsers are launched and tests are executed.

Prerequisites

  • Java JDK 8+

  • Maven

  • Docker (for Grid setup)

  • Eclipse

  • Basic understanding of Selenium

Step 1: Set up Selenium Grid using Docker
Using Docker CLI

docker network create grid
docker run -d -p 4444:4444 --net grid --name selenium-hub selenium/hub
docker run -d --net grid --name chrome-node -e HUB_HOST=selenium-hub selenium/node-chrome
docker run -d --net grid --name firefox-node -e HUB_HOST=selenium-hub selenium/node-firefox

Verify Grid UI to see if the Hub and Nodes are working
Visit http://localhost:4444/grid in your browser to check if the Hub and Nodes are running.

Step 2: Create a Java Selenium Test
Set up a Maven project with the following dependency

<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.34.0</version>
    </dependency>
</dependencies>

Step 3: Write Test Code to Run on the Grid

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.net.URL;

public class GridTest {
    public static void main(String[] args) throws Exception {
        // URL of the Grid Hub
        URL gridUrl = new URL("http://localhost:4444/wd/hub");

        // Browser capability (can be "chrome" or "firefox")
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setBrowserName("chrome");

        // Create RemoteWebDriver
        WebDriver driver = new RemoteWebDriver(gridUrl, capabilities);

        // Run test
        driver.get("https://example.com");
        System.out.println("Title: " + driver.getTitle());

        driver.quit();
    }
}

Step 4: Run Tests in Parallel
You can use a test framework like TestNG to run multiple tests in parallel.

<suite name="GridSuite" parallel="tests" thread-count="2">
    <test name="ChromeTest">
        <parameter name="browser" value="chrome"/>
        <classes>
            <class name="tests.GridTest"/>
        </classes>
    </test>
    <test name="FirefoxTest">
        <parameter name="browser" value="firefox"/>
        <classes>
            <class name="tests.GridTest"/>
        </classes>
    </test>
</suite>
0
Subscribe to my newsletter

Read articles from Prashant Dhotre directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prashant Dhotre
Prashant Dhotre