0
0
Selenium Javatesting~5 mins

Selenium Grid setup in Selenium Java

Choose your learning style9 modes available
Introduction

Selenium Grid lets you run tests on many computers and browsers at the same time. This saves time and checks your app works everywhere.

You want to test your website on Chrome, Firefox, and Edge at once.
You need to run tests on different operating systems like Windows and Linux.
You want to speed up testing by running many tests in parallel.
You have a team and want to share test machines easily.
You want to avoid running tests only on your local computer.
Syntax
Selenium Java
java
// Start the Hub
java -jar selenium-server-4.2.0.jar hub

// Start a Node and connect to Hub
java -jar selenium-server-4.2.0.jar node --hub http://localhost:4444

// In your test code
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), new ChromeOptions());

The Hub is the central server that controls test requests.

Nodes are machines that run the browsers for tests.

Examples
This command starts the Selenium Grid Hub on your local machine.
Selenium Java
// Start Hub on default port 4444
java -jar selenium-server-4.2.0.jar hub
This command starts a Node that registers itself to the Hub at the given URL.
Selenium Java
// Start Node and connect to Hub
java -jar selenium-server-4.2.0.jar node --hub http://localhost:4444
This Java code creates a WebDriver that runs tests on the Grid Hub using Chrome browser.
Selenium Java
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), new ChromeOptions());
Sample Program

This Java program connects to a Selenium Grid Hub running locally. It opens the Chrome browser on a Node, navigates to example.com, prints the page title, and closes the browser.

Selenium Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.net.URL;

public class GridTest {
    public static void main(String[] args) throws Exception {
        // Set Chrome options
        ChromeOptions options = new ChromeOptions();

        // Connect to Selenium Grid Hub
        WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), options);

        // Open a website
        driver.get("https://example.com");

        // Print the page title
        System.out.println("Title: " + driver.getTitle());

        // Close the browser
        driver.quit();
    }
}
OutputSuccess
Important Notes

Make sure the Hub and Node are running before starting your test.

Use matching browser drivers on Nodes (like chromedriver for Chrome).

Check firewall settings to allow communication between Hub and Nodes.

Summary

Selenium Grid helps run tests on many browsers and machines at once.

Start a Hub and connect Nodes to it before running tests.

Use RemoteWebDriver in your test code to run tests on the Grid.