World’s largest virtual agentic engineering & quality conference

WHENAUG 19-21
WHEREVirtual · Global
Register Now
AutomationSelenium JavaTutorial

Selenium With Java: A Hands-On Automation Tutorial [2026]

A practical guide to Selenium with Java covering environment setup, Maven configuration, TestNG test structure, the Page Object Model, and parallel cloud execution.

Author

Salman Khan

Author

Author

Srinivasan Sekar

Reviewer

Published on: August 1, 2025

Last Updated on: June 14, 2026

Selenium with Java is the most widely used pairing in UI test automation. Java contributes static typing, mature build tooling, and a deep ecosystem, while Selenium WebDriver handles cross-browser control.

Together they support suites that scale to thousands of cases and survive years of refactoring. This guide follows one example end to end: set up the environment, write a test, walk through the code, then scale it to parallel cloud execution.

TL;DR

To automate browser testing, use Selenium with Java to build maintainable, statically typed test suites, and run them in parallel on TestMu AI's cloud infrastructure. This combination allows teams to programmatically control browsers through code and execute scalable tests across various browser and operating system combinations.

Why Use Selenium With Java

  • Browser control: Selenium is an open-source framework that automates web browsers through code, allowing teams to programmatically execute UI tests.
  • Test suite maintenance: Java is a statically typed programming language that provides a mature ecosystem and broad library support to keep large test suites maintainable over time.

How Do You Run Selenium Tests With Java?

  • Dependency management: Maven is a build tool that manages project dependencies in a pom.xml file, ensuring all developers and CI runners build from identical library versions.
  • Test execution: TestNG is a testing framework that structures test classes, configures execution suites via testng.xml, and generates detailed pass, fail, and skip reports.
  • Driver management: Selenium Manager ships inside the Selenium client from version 4.6 onward and resolves the matching browser driver automatically, removing the need for a separate driver-manager dependency.
  • Parallel cloud execution: TestMu AI is a cloud-based automated browser testing infrastructure that runs Selenium Java tests in parallel across different browser and OS combinations to cut runtime.

Why Use Selenium With Java for Automation

Teams use Selenium with Java because Java's static typing, mature Maven build tools, and large ecosystem make test suites scalable and maintainable over years of continuous UI changes.

Selenium is the open-source framework automating the browser; Java is the language enterprise teams most often pair it with.

Three integrations shape how the suite is structured, executed, and scaled:

  • TestNG and JUnit 5 for modular execution, parameterization, and assertions. TestNG's suite-level parallelism, flexible grouping, and rich TestNG annotations for Selenium WebDriver make it the more common pick for large suites; JUnit 5 is often preferred when the team already lives in that ecosystem, and the JUnit tutorial covers setup and annotations for teams making that choice.
  • Selenium-Jupiter for advanced JUnit 5 integration, useful if you want declarative driver injection.
  • Docker-based Selenium Grid for parallel execution in CI/CD, though most teams move to a managed cloud grid before maintaining their own Grid infrastructure long term.

How to Set Up Selenium With Java

To set up Selenium with Java, install the JDK, pick an IDE such as Eclipse or IntelliJ, add the Selenium client library through Maven, and configure browser drivers automatically with Selenium Manager.

Getting these right up front avoids the classpath and driver-mismatch errors behind most failed first runs.

  • Java Development Kit (JDK): Install a current LTS release such as JDK 17 or 21 from Oracle JDK or OpenJDK. Match the version to what your CI runners use, since a local JDK 21 build that fails on a JDK 17 runner is a common and avoidable surprise.
  • An IDE: Eclipse or IntelliJ IDEA. Most teams have standardized on IntelliJ, but either manages project structure, classpath, and execution fine.
  • Selenium Java client library: Pull it through Maven rather than adding JARs manually. Manual JARs work for a first script but become unmanageable the moment you add a second dependency.
  • Browser drivers: Selenium 4.6+ ships Selenium Manager, which resolves drivers automatically, so manual driver downloads are largely obsolete.

Once the JDK is installed, set the environment variables so the toolchain can resolve Java:

  • Open Edit the system environment variables, then click Environment Variables.
  • Under System variables, click New.
  • Set the variable name to JAVA_HOME for a JDK install, or JRE_HOME for a runtime-only install. For automation work you want the JDK, not just the JRE.
  • Set the value to your JDK installation path, then apply the changes.

Confirm with java -version in a terminal. If the version printed does not match the JDK you intended, your PATH is resolving an older install first, which is worth fixing now rather than debugging later.

Note

Note: Run Selenium Java tests across 10,000+ browser and OS combinations without managing infrastructure. Try TestMu AI Today!

How to Create a Selenium Java Project in Eclipse

To create a Selenium Java project in Eclipse, open a new Java project, add a package and class, then add the Selenium JARs to the build path. The steps below walk through it; IntelliJ follows the same flow.

  • Open Eclipse and select a workspace directory.
  • Create a Java project: File > New > Java Project, name it (for example, SeleniumDemo), and finish.
  • Add a package and class: Right-click src > New > Package (for example, com.test.selenium), then add a class inside it. Resist the urge to drop everything in the default package; a flat structure becomes unworkable past a handful of tests.
  • Add the Selenium JARs: Right-click the project > Build Path > Configure Build Path > Libraries > Add External JARs, then select every Selenium JAR including those in libs. Apply and close.

That manual JAR path is fine to see once, but in any real project use Maven instead. A pom.xml declares dependencies, pins versions so every machine and CI runner builds identically, and ends the "works on my machine" class of failures.

This is the whole dependency block you need. Selenium 4.46.0 and TestNG 7.12.0 are the current releases on Maven Central as of August 2026:

<dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>4.46.0</version>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.12.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <suiteXmlFiles>
                    <suiteXmlFile>testng.xml</suiteXmlFile>
                </suiteXmlFiles>
            </configuration>
        </plugin>
    </plugins>
</build>

Two details save time later. Pin exact versions rather than using a range, because a silent minor bump is a miserable thing to debug when a suite starts failing overnight. And wire testng.xml into the Surefire plugin now, since that is what lets mvn test run the whole suite in CI instead of one class at a time.

Notice there is no driver-manager dependency in that block. Selenium Manager has shipped with every Selenium release since 4.6 and acts as a fallback: when no driver is supplied on the PATH or through a system property, it resolves and downloads the matching one for you. The Selenium project still labels it beta, so keep manual driver management as an option if your CI runners are locked down, but for most projects the extra dependency is no longer needed.

Skip the setup and install the Selenium Skill for Claude Code, Copilot & Cursor with one command.

Selenium

How to Write and Run Your First Selenium Java Test

To write and run a Selenium Java test, create a TestNG class that initializes WebDriver, define a test method with your browser actions, and run it from the IDE or with mvn test.

The example below is intentionally minimal so the WebDriver mechanics stay visible: launch Chrome, open Selenium Playground, verify the H1, then close the browser.

package TestMuAI;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class FirstTestScriptUsingWebDriver {
    public static WebDriver driver = null;

    @BeforeTest
    public void setUp() {
        driver = new ChromeDriver();
    }

    @Test
    public void firstTestCase() {
        driver.get("https://www.testmuai.com/selenium-playground/");
        WebElement pageH1 = driver.findElement(By.tagName("h1"));
        Assert.assertEquals(pageH1.getText(), "Selenium Playground");
        System.out.println("H1 verified: " + pageH1.getText());
    }

    @AfterTest
    public void closeBrowser() {
        driver.quit();
        System.out.println("The driver has been closed.");
    }
}

Dependencies come from the pom.xml shown earlier, declaring Selenium and TestNG, with the compiler set to Java 17. A minimal testng.xml registers the class so the suite runs. Each step prints to the console on execution.

Code Walkthrough:

  • @BeforeTest runs setup once before all tests in a <test> tag. For per-test isolation you usually want @BeforeMethod instead, so each test case gets a clean browser and one failure does not cascade into the next.
  • public static WebDriver driver works for a single test but is a liability in parallel runs. A shared static driver means threads contend for one browser session. In production you isolate it with ThreadLocal<WebDriver> so each thread owns its instance.
  • new ChromeDriver() with no driver setup line. Older tutorials call WebDriverManager.chromedriver().setup() here. On Selenium 4.6 and later that line is redundant, because Selenium Manager resolves the driver natively when none is on the PATH.
  • driver.get("URL") navigates and blocks until the page load event fires, which is not the same as the element being interactable, hence waits below.
  • driver.findElement(By.tagName("h1")) locates by tag name and is fine for a unique element like an H1. For everything else, prefer stable locators in Selenium WebDriver such as id, name, or data-testid hooks over tag-based or absolute XPath selectors.
  • @AfterTest with driver.quit() ends the session and shuts down the driver process. Reach for quit() rather than close() in teardown, because close() only closes the current window and can leave the session orphaned, which is a top cause of resource leaks on a grid.
  • No try/catch around the assertion. This one is deliberate. Wrapping a test body in catch (Exception e) {} swallows the failure and reports green, so a broken test looks like a passing one. Let the exception propagate; a test that cannot fail is worse than no test.

Run the test locally from the project root:

mvn test -Dtest=FirstTestScriptUsingWebDriver

How to Run Parallel Selenium Java Tests on the Cloud

To run parallel Selenium Java tests on the cloud, add browser and platform parameters to testng.xml, point the driver at the cloud grid hub, and pass your authentication capabilities including username, access key, and browser version.

A local run only validates one browser on one machine, and past a few parallel threads the local machine becomes the bottleneck. A cloud grid removes that ceiling, provided your driver is thread-safe.

TestMu AI (Formerly LambdaTest) Automation Cloud is a cloud-based automated browser testing infrastructure that runs Selenium Java tests across different browser and OS combinations, with parallel execution to cut total runtime.

Features:

  • Parallel execution at scale: Run hundreds of tests simultaneously across 10,000+ browser and OS combinations, cutting suite runtime from hours to minutes.
  • Complete session artifacts: Every run automatically generates video recordings, network logs, console logs, and screenshots with no extra configuration needed.
  • SmartWait: Runs actionability checks before each interaction so elements are visible, enabled, and stable, eliminating the need for explicit wait commands in test scripts.
  • Auto Healing: Detects broken locators caused by DOM changes and automatically reformulates them during execution, keeping tests running through UI updates without manual script fixes.
  • 120+ CI/CD integrations: Native support for Jenkins, GitHub Actions, GitLab CI, Azure DevOps, CircleCI, and 115+ other pipeline tools.

For the full configuration reference, see how to run Selenium Java tests on TestMu AI.

Test infrastructure that does not break, from TestMu AI

The test logic stays the same; you parameterize the environment in testng.xml:

<test name="WIN11TEST">
    <parameter name="browser" value="chrome"/>
    <parameter name="version" value="latest"/>
    <parameter name="platform" value="Windows 11"/>
    <classes>
        <class name="FirstTestScriptUsingWebDriver"/>
    </classes>
</test>
<test name="MACTEST">
    <parameter name="browser" value="safari"/>
    <parameter name="version" value="latest"/>
    <parameter name="platform" value="macOS Sequoia"/>
    <classes>
        <class name="FirstTestScriptUsingWebDriver"/>
    </classes>
</test>

This configuration does the following:

  • <test> blocks define one parallel execution lane each, so the browsers run concurrently.
  • browser and version set the target browser and its version per lane.
  • platform pins the operating system the browser runs on.
  • <class> points each lane at the same test class, so one test runs across all environments.

Then point the driver at the grid hub and pass your capabilities:

ChromeOptions browserOptions = new ChromeOptions();
browserOptions.setPlatformName("Windows 11");
browserOptions.setBrowserVersion("latest");
HashMap<String, Object> ltOptions = new HashMap<String, Object>();
ltOptions.put("username", "YOUR_LT_USERNAME");
ltOptions.put("accessKey", "YOUR_LT_ACCESS_KEY");
ltOptions.put("project", "Selenium with Java");
ltOptions.put("w3c", true);
ltOptions.put("plugin", "java-testNG");
browserOptions.setCapability("LT:Options", ltOptions);

The capabilities block configures the cloud session:

  • setPlatformName and setBrowserVersion declare the target OS and browser version.
  • username and accessKey authenticate the run, pulled from environment variables.
  • project tags results for grouping in the dashboard.
  • w3c and plugin set the protocol and framework binding for correct reporting.

Keep the username and access key in environment variables, never hardcoded, since committed credentials in a test repo are a routine security finding. Run with mvn test -D suite=parallel.xml, then review results in the Web Automation dashboard.

What Are Advanced Use Cases of Selenium With Java

Advanced Selenium Java use cases include automating registration forms, handling authentication pop-ups, managing CAPTCHAs, uploading and downloading files, and handling cookies.

Each becomes a source of flaky test failures once you move past a basic happy-path script.

  • Form and registration automation: Validate titles, navigate links, submit valid and invalid inputs, and assert redirection. The trap is asserting on timing rather than state; wait for the confirmation element, not a fixed delay.
  • DOM refreshes mid-interaction also cause handling stale element exceptions in Selenium Java to become a routine part of form test maintenance.

  • Authentication pop-ups: Browser-level credential prompts live outside the DOM, so findElement cannot reach them. Handling login popup in Selenium requires either the URL credential pattern or browser-level options, not DOM interaction.
  • CAPTCHA handling: Selenium cannot and should not try to solve CAPTCHAs. In practice you disable or stub them in test environments rather than automate around them.
  • Broken link detection: Collect all anchor elements on the page, extract each href, and check the HTTP response code. Broken links testing using Selenium flags 4xx and 5xx responses without requiring any user interaction on the page.
  • File upload and download: Knowing how to upload and download files in Selenium saves significant debugging time: uploads use sendKeys on the file input, while downloads need a ChromeOptions download directory and file system polling, not a fixed wait.
  • Cookie management: Add, delete, and read cookies to test sessions and personalized state; handling cookies in Selenium WebDriver is also the fastest way to bypass slow login flows by injecting a valid session cookie instead of navigating through the UI each time.

What Are the Best Practices for Selenium Java Testing

The core Selenium Java best practices are designing test cases before scripting, using the Page Object Model, choosing stable locators, adding logging and reporting, and using explicit waits instead of Thread.sleep().

Apply them from the first test, since retrofitting across hundreds of cases is significantly more costly.

  • Design test cases before scripting. Decide coverage from the user's perspective first; automating an ill-defined scenario just encodes the ambiguity.
  • Use the Page Object Model. Centralizing locators and actions in Page Object classes confines a UI change to one file. Without it, a single redesign can touch every test you own.
  • Choose stable locators. Prefer id, name, or data-testid hooks; fall back to scoped CSS before XPath, and avoid absolute XPath and text-based locators entirely. Locator strategy is the single biggest lever on flakiness.
  • Add logging and reporting. Selenium ships neither. Integrate TestNG reporting or Allure, and capture screenshots in Selenium on every failure so a red result is debuggable without a rerun.
  • Never use Thread.sleep(). It either wastes time or fails under load. Replace every sleep with a Selenium waits pattern: WebDriverWait with ExpectedConditions keyed to the actual element state.
  • Use an AI agent to write Selenium tests. Teams using Selenium AI approaches pair agents like Claude Code or Cursor with Selenium Skill, a context file that gives the agent the locator strategy, wait rules, and Page Object structure it needs to generate maintainable tests instead of fragile boilerplate.

Conclusion

Selenium with Java is still the default for durable UI automation testing, and the path from first script to scaled coverage is short if you avoid the traps along the way.

You set up the environment, wrote a working WebDriver test, saw exactly where that sample code would fail in production, and scaled the corrected approach to parallel execution across browsers with only configuration changes.

The next steps that separate a maintainable suite from a fragile one are consistent: a thread-safe driver, the Page Object Model across the suite, stable locators, explicit waits over sleeps, and a cloud grid so coverage grows without local overhead. Build on those and the suite keeps paying off long after the first test.

Author

...

Salman Khan

Blogs: 141

  • Twitter
  • Linkedin

Salman is a Test Automation Evangelist and Community Contributor at TestMu AI, with over 6 years of hands-on experience in software testing and automation. He has completed his Master of Technology in Computer Science and Engineering, demonstrating strong technical expertise in software development, testing, AI agents and LLMs. He is certified in KaneAI, Automation Testing, Selenium, Cypress, Playwright, and Appium, with deep experience in CI/CD pipelines, cross-browser testing, AI in testing, and mobile automation. Salman works closely with engineering teams to convert complex testing concepts into actionable, developer-first content. Salman has authored 120+ technical tutorials, guides, and documentation on test automation, web development, and related domains, making him a strong voice in the QA and testing community.

Reviewer

...

Srinivasan Sekar

Reviewer

  • Linkedin

Srinivasan Sekar is Director of Engineering at TestMu AI (formerly LambdaTest), where he leads engineering and open-source initiatives behind the Selenium and Appium automation grid and owns TestMu AI's MCP Server. A committer to Appium and a contributor to Selenium, WebdriverIO, Taiko, and AppiumTestDistribution, he brings over 15 years of experience in quality engineering and open-source technologies. He is the author of the Apress book 'The MCP Standard: A Developer's Guide to Building Universal AI Tools with the Model Context Protocol,' a Certified Kubernetes and Cloud Native Associate, and an international conference speaker. Before TestMu AI he spent over eight years at Thoughtworks as a Principal Consultant and Quality Architect. Srinivasan holds a B.Tech in Information Technology from Anna University.

Open in ChatGPT Icon

Open in ChatGPT

Open in Claude Icon

Open in Claude

Open in Perplexity Icon

Open in Perplexity

Open in Grok Icon

Open in Grok

Open in Gemini AI Icon

Open in Gemini AI

Copied to Clipboard!
...

3000+ Browsers. One Platform.

See exactly how your site performs everywhere.

Try it free
...

Write Tests in Plain English with KaneAI

Create, debug, and evolve tests using natural language.

Try for free
...
TestMu Conf 2026

World's largest virtual agentic engineering & quality conference

...

AUG 19-21, 2026

REGISTER NOW

Selenium With Java FAQs

Did you find this page helpful?

More Related Blogs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests