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

Test your website on
3000+ browsers

Get 100 minutes of automation
test minutes FREE!!

Test NowArrowArrow

KaneAI - GenAI Native
Testing Agent

Plan, author and evolve end to
end tests using natural language

Test NowArrowArrow
AutomationSelenium JavaTutorial

How to Use Selenium With Java: A Complete Tutorial

Dive into automation testing using Selenium with Java with this detailed tutorial. Master the essentials to begin your Selenium Java testing journey confidently.

Author

Salman Khan

December 26, 2025

Selenium with Java is a widely adopted approach for automating web application testing. It combines the robustness of the Selenium framework with Java’s reliability and strong ecosystem, enabling efficient creation and execution of tests across different web environments.

Overview

Selenium with Java is widely used in automation due to Java’s stability, mature tooling, and strong ecosystem support. Its seamless integration with testing frameworks and CI tools makes it ideal for scalable, maintainable test suites.

How to Configure Selenium With Java?

Before you begin automating with Selenium, it helps to understand the basic setup that ensures smooth development. Each step below prepares your environment for testing.

    • Setup Requirements: Install the Java Development Kit, verify system readiness, and make sure the environment variables are configured correctly.
    • IDE Preparation: Use an editor like IntelliJ IDEA or Eclipse, set it up for Java work, and organize your workspace for smooth development.
    • Libraries and Drivers: Download the Selenium Java files and the browser drivers you need so your tests can interact with different browsers.
    • Project Configuration: Create a new Java project and include the Selenium JAR files in your classpath to enable WebDriver usage.
    • Script Development: Write your Selenium WebDriver scripts, structure them clearly, and run them to verify browser behavior and test flow.

    How to Run Selenium Test With Java?

    Before running automated tests with Selenium and TestNG, it’s helpful to set up a clear workflow. The steps below outline how to prepare your environment, build your test structure, and validate the execution.

    • Environment Setup: Install the JDK, choose an IDE such as Eclipse or IntelliJ, and include Selenium through your pom.xml for dependency management.
    • Test Class Creation: Build a TestNG class that initializes Selenium WebDriver along with ChromeDriver to handle browser actions.
    • Scenario Implementation: Write a flow that launches the browser, opens the signup page, and triggers the Sign In action to validate interaction.
    • Suite Configuration: Use a testng.xml file to organize your tests, define groups, and manage how the suite runs on your local machine.
    • Execution and Validation: Run the suite through your IDE or by using mvn test, then review the results to confirm everything behaves as expected.

    Why Use Selenium With Java for Automation?

    Selenium is a powerful open-source automation framework used for testing modern web applications across browsers, operating systems, and platforms. While it supports multiple programming languages, Selenium with Java is the preferred choice in enterprise environments due to Java’s mature ecosystem, static typing, and strong community support.

    Its compatibility with build tools like Maven and Gradle, and IDEs like IntelliJ and Eclipse, makes Java ideal for building structured, scalable test automation frameworks. The widespread adoption of Java ensures long-term support and a large pool of experienced developers.

    Key integrations that strengthen Selenium with Java include:

    • TestNG and JUnit5 for flexible and modular test execution.
    • Selenium-Jupiter for advanced JUnit5 integration.
    • Support for Docker-based Selenium Grids to enable scalable, parallel test execution in CI/CD environments.

    Together, Selenium and Java offer a stable foundation for creating reliable, maintainable UI test suites that scale with application complexity.

    How to Use Selenium With Java?

    To start your automation testing journey using Selenium with Java, the first step is to install and configure Selenium onto your local system. In this section of this article on Selenium with Java, I will guide you through the installation process step by step. You will also learn how to create a basic Selenium with Java project setup.

    Installation

    The installation process consists of the following steps.

    • Install JDK: You can download JDK from any of the below options:
    • Install Eclipse IDE: You can download the latest version from the Eclipse Downloads Page Alternatively, you can also use any other popular IDE like Jetbrains Webstorm, IntelliJ IDEA, etc.
    • Install Selenium WebDriver and Language Bindings: Download the Selenium Client Library for Java from the Selenium Downloads Page. The download comes as a ZIP file. Extract the contents (JAR files) and store them in a directory.
    • Install Browser Drivers (Optional): You can download the drivers for the browsers of your choice from the Selenium Ecosystem Page.

    Setup Environment Variable

    Once the installation is complete, set the environment variables. The steps are as follows:

    • Search for environment variables, then click on the search result that says Edit the system environment variables.
    • Click on Environment Variables.
    • Click New under System variables.
    • In the Variable name field, enter either
      • JAVA_HOME, if you have installed the Java Development Kit (JDK).
      • JRE_HOME, if you have installed the Java Runtime Environment (JRE).
    • In the Variable value field, provide your JDK or JRE installation path.
    • Click OK and then Apply Changes.

    The environment variable setup is now complete. Open the command prompt and run the command java -version to verify that Java has been successfully installed in your system. Once verified, you can proceed to the next step: setting up your project.

    How to Create a Selenium With Java Project in Eclipse?

    You need to set up a project to write and store your test cases. Follow the steps below to create a new Selenium with Java project in Eclipse.

    • Open Eclipse IDE : Launch Eclipse and select your workspace directory.
    • Create a New Java Project :
      • Go to File > New > Java Project
      • Enter a project name (e.g., SeleniumDemo)
      • Click Finish
    • Create a Package and Class
      • Right-click on src > New > Package (e.g., com.test.selenium)
      • Right-click on the package > New > Class
      • Name the class (e.g., LoginTest) and check public static void main(String[] args)
      • Click Finish
    • Add Selenium JAR Files:
    • Right-click on the project > Build Path > Configure Build Path.
    • Go to the Libraries tab > Click Add External JARs.
    • Select all Selenium JAR files from the downloaded Selenium folder (selenium-java-x.xx.x).
    • Include both the main JARs and those inside the libs folder.
    • Click Apply and Close

    With your Selenium with Java project configured, you’re now ready to write and run your first test script.

    To perform automated testing using Selenium with Java, you can also leverage Maven. Maven is one of the popular Java build tools that relies on POM.xml. If you are new to Maven, check out this Selenium Maven tutorial, which guides you through writing and running Selenium projects with Maven.

    Demo: Running Test Using Selenium With Java on Local

    In this section, you will learn how to write and execute your first Selenium test using Java on your local machine. This will cover setting up your environment, creating a simple test script, and running it with a local browser.

    Test Scenario

    Implementation

    package LambdaTest;
     
    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.annotations.AfterTest;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Listeners;
    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 {
               System.out.println("Launching LambdaTest Sign In Page");
               driver.get("https://accounts.lambdatest.com/register");
               WebElement pageHeader= driver.findElement(By.xpath("//a[text()='Sign In']"));
               pageHeader.click();
               System.out.println("Clicked on the Sign In Button.");
           } catch (Exception e) {
           }
       }
       @AfterTest
       public void closeBrowser() {
           driver.close();
           System.out.println("The driver has been closed.");
       }
    }
    
    ...

    To import the required dependencies, you can use the below pom.xml file.

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
     
      <groupId>org.example</groupId>
      <artifactId>LambdaTest</artifactId>
      <version>1.0-SNAPSHOT</version>
      <dependencies>
               <dependency>
              <groupId>org.seleniumhq.selenium</groupId>
              <artifactId>selenium-chrome-driver</artifactId>
              <version>4.1.1</version>
          </dependency>
          <dependency>
              <groupId>org.testng</groupId>
              <artifactId>testng</artifactId>
              <version>7.4.0 </version>
          </dependency>
          <dependency>
              <groupId>io.github.bonigarcia</groupId>
              <artifactId>webdrivermanager</artifactId>
              <version>5.0.3</version>
          </dependency>
      </dependencies>
     
      <properties>
          <maven.compiler.source>17</maven.compiler.source>
          <maven.compiler.target>17</maven.compiler.target>
      </properties>
    </project>
    

    Test Execution

    To run the above test case using Selenium with Java on a local grid, you can use the below testng.xml file:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
    <suite  name="FirstTestScriptUsingWebDriverSuite">
       <test name="FirstTestScriptUsingWebDriver" >
           <classes>
               <class name="LambdaTest.FirstTestScriptUsingWebDriver" >
               </class>
           </classes>
       </test>
    </suite>
    

    Code Walkthrough

    Here is the code walkthrough of the executed test on a local grid using Selenium with Java.

    • @BeforeTest: Responsible for executing setup steps before any test method.
    • WebDriverManager.chromedriver().setup(): Responsible for setting up the ChromeDriver automatically.
    • driver.get(“URL”): Responsible for opening the specified URL in the browser.
    • @Test: Responsible for marking the method as a test case.
    • try { … } catch (Exception e) { … }: Responsible for handling any runtime exceptions.
    • driver.findElement(By.xpath(“…”)).click(): Responsible for clicking the element located by the XPath.
    • System.out.println(“message”): Responsible for printing a message to the console.
    • @AfterTest: Responsible for executing cleanup steps after all test methods.
    • driver.close(): Responsible for closing the current browser window.
    • driver.quit(): Responsible for closing all browser windows and ending the WebDriver

    Achieving consistent browser coverage in Selenium Java testing is tough due to flaky tests from dynamic content, timing issues, and varying environments. Cloud platforms like TestMu AI solve this with stable real-device infrastructure, reducing flakiness and enabling reliable, scalable testing with logs and debugging tools.

    Demo: Running Parallel Tests Using Selenium With Java on Cloud

    TestMu AI is a GenAI-native test execution platform that lets you perform both manual and Selenium Java automation testing using various test automation frameworks simultaneously across 3000+ browser and OS combinations. The platform enables parallel testing in Selenium, enhancing scalability and reducing test execution time with a simple setup and minimal configuration.

    ...

    The same sign in scenario will be exeuting on cloud platfrom on parallel broswers will be using firefox , chrome, safari browser , all you need to do it making few changes to your exsisting testng.xml file as shown below:

    <test name="WIN8TEST">
            <parameter name="browser" value="firefox"/>
            <parameter name="version" value="120.0"/>
            <parameter name="platform" value="WIN8"/>
            <classes>
                <class name="FirstTestScriptUsingWebDriver"/>
            </classes>
        </test> <!-- Test -->
        <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 -->
        <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> <!-- Test -->
    

    Once you’ve added your parameters, update your test script to connect using the TestMu AI Grid URL:

    gridURL = "@hub.lambdatest.com/wd/hub"
    

    Next, configure the TestMu AI capabilities. Set your TestMu AI Username and Access Key as environment variables, and define automation capabilities such as browser, browser version, platform, and other settings as shown below:

    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);
    

    You can generate the above Selenium Java capabilities from the TestMu AI Automation Capabilities Generator.

    By running your Selenium Java tests on TestMu AI’s cloud infrastructure, you avoid the overhead of maintaining local setups. With support for parallel execution, it helps you scale efficiently, reduce test execution time, and accelerate your release cycles, all with minimal configuration.

    To get started, refer to the documentation on Selenium Java testing with TestMu AI.

    Test Execution

    To run the tests for the cloned repository, run the following command.

    mvn test -D suite=parallel.xml
    

    Now, go to your TestMu AI Web Automation Dashboard to see your parallel test results.

    LT-output

    Advanced Use Cases of Using Selenium With Java

    Apart from the basic test scenarios, there are also advanced test cases you can perform using Selenium with Java that go beyond standard validations. These include automating complex, real-world interactions across modern web applications.

    • Automating Registration Page: Automate the registration page using Selenium with Java by validating the page title, navigating links, handling valid and invalid form inputs, and verifying redirection to the email verification page.
    • Handling Login Popups: Another advanced use case involves handling authentication pop-ups using Selenium with Java. These browser-level pop-ups require entering credentials and are used to restrict access to protected areas of a website.
    • Handling Captcha: CAPTCHA is used to prevent automated bots from accessing services or collecting data. While Selenium with Java can’t solve captchas directly, it can detect them and support alternative flows for handling CAPTCHA, such as manual intervention or third-party integrations.
    • Uploading and Downloading Files: Uploading and downloading file handling is a common scenario in test automation. With Selenium and Java, you can automate upload flows (like video uploads on YouTube) and validate downloads (such as invoices on Amazon), ensuring these features work as expected.
    • Handling Cookies: Cookies store user data to maintain sessions and preferences. With Selenium and Java, you can add, delete, or retrieve cookies during test execution, enabling better handling cookies for validating personalized experiences and session management.
    ...

    Best Practices for Selenium Java Testing

    Selenium Java automation helps reduce manual effort, speed up execution, detect bugs early, improve coverage, and accelerate time to market.

    However, test flakiness and incorrect approaches can make tests unreliable. Tools like HyperExecute by TestMu AI address these issues by reducing execution time and enabling faster debugging.

    • Planning and Designing Test Cases Beforehand: Create a proper test plan before writing automation scripts. Ensure maximum test coverage by considering all possible logical scenarios from the end-user perspective.

    • Implementing Page Object Model: UI changes often affect Selenium locators. Using POM helps centralize web elements and actions into dedicated Page Object classes, reducing code duplication and simplifying maintenance. Changes to the UI require updates only in the relevant Page Object Model (POM), not across all test cases.
    • Choosing the Best-Suited Locators: Use stable locators like ID or Name when available. Avoid brittle locators like XPath if the UI changes frequently. Choosing the right locator reduces test maintenance and improves reliability.
    • Implement Logging and Reporting: As test suites grow, identifying failures becomes harder. Use logging and reporting (e.g., via TestNG) to track test results, capture errors, and include screenshots. Selenium doesn’t include reporting by default, so integrate external libraries to generate useful reports.
    • Incorporating Wait Commands: Avoid using Thread.sleep() for delays. It adds unnecessary wait time or causes failures due to inaccurate delays. Use Selenium’s implicit or explicit waits to handle element loading more efficiently based on actual conditions.
    • TestMu AI offers a SmartWait feature that runs a series of “actionability checks” on webpage elements before executing any action. These checks verify visibility, presence, and interactability to ensure elements are ready for actions like clicking or typing, resulting in more stable and reliable web automation tests.

    • Auto-Healing: Auto-healing in Selenium helps manage synchronization issues by adapting to dynamic changes in web elements. It automatically adjusts wait times and allows test scripts to continue even when elements change or load unpredictably, reducing flakiness and improving test stability.
    • Watch this video tutorial on Auto-healing in web automation by Anton Angelov (@angelovstanton), Co-founder & CTO of Automate The Planet, Forbes-featured test automation expert and best-selling author.

    Conclusion

    Selenium with Java is the most widely adopted test automation combination among QAs. In this tutorial, we explored how to start with Selenium Java automation testing and wrote our first test case.

    On top of that, we also learned how to optimize test execution by leveraging parallel testing and other best practices to establish a reliable testing cycle. I hope this tutorial turns out to be beneficial. There’s much more to explore!

    Author

    Salman is a Test Automation Evangelist and Community Contributor at TestMu AI, with over 5 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 and testing. 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.

    Frequently asked questions

    Did you find this page helpful?

    More Related Hubs

    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