Hero Background

Next-Gen App & Browser Testing Cloud

Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Next-Gen App & Browser Testing Cloud
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

June 17, 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.

Overview

Why Use Selenium With Java

Selenium is an open-source framework that controls browsers through code. Teams choose Java as the pairing language for its static typing, Maven build ecosystem, and broad library support, all of which keep large test suites maintainable over time.

How Do You Run Selenium Tests With Java?

Getting a Selenium Java test running takes five steps, from project setup to reviewing results.

  • Create a Maven project: Add Selenium, TestNG, and WebDriverManager as dependencies in pom.xml so every developer and CI runner builds from the same library versions.
  • Write the test class: Structure each test with a setup method to open the browser, a test method for your actions and assertions, and a teardown method to close the session.
  • Configure the suite: Register your test classes in testng.xml to control which tests run, in what order, and across which browsers or platforms.
  • Run from the terminal: Execute mvn test from the project root; Maven picks up the suite file, runs all registered tests, and outputs a results report on completion.
  • Review results: TestNG generates a report showing pass, fail, and skip counts with stack traces for any failures, making it easy to identify what broke and why.

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.

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 io.github.bonigarcia.wdm.WebDriverManager;
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() throws Exception {
        WebDriverManager.chromedriver().setup();
        driver = new ChromeDriver();
    }

    @Test
    public void firstTestCase() {
        try {
            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());
        } catch (Exception e) {
        }
    }

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

Dependencies come from a pom.xml declaring Selenium, TestNG, and WebDriverManager, 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.
  • WebDriverManager.chromedriver().setup() auto-provisions the driver binary. On Selenium 4.6+ this is often redundant because Selenium Manager handles it natively.
  • 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.close() closes the current window. Use driver.quit() in teardown instead; close() can leave the driver process and session orphaned, and orphaned sessions are a top cause of resource leaks on a grid.
  • catch (Exception e) {} is the worst offender. An empty catch swallows the failure, so a broken test reports green. Never ship this; let the exception propagate or assert explicitly so failures actually fail.

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="WIN10TEST">
    <parameter name="browser" value="chrome"/>
    <parameter name="version" value="121.0"/>
    <parameter name="platform" value="WIN10"/>
    <classes>
        <class name="FirstTestScriptUsingWebDriver"/>
    </classes>
</test>
<test name="MACTEST">
    <parameter name="browser" value="safari"/>
    <parameter name="version" value="11.0"/>
    <parameter name="platform" value="macos 10.13"/>
    <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 10");
browserOptions.setBrowserVersion("121.0");
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: 122

  • 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.

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

Frequently asked questions

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