- What is Selenium with Java?
- Why Use Selenium with Java for Automation Testing
- How Selenium WebDriver Works
- How to Use Selenium with Java for Web Automation Testing
- Write Your First Selenium Test in Java with Eclipse IDE
- Handling Alerts, Frames, and Multiple Windows/Tabs
- Introduction to TestNG Framework
- Conclusion
- Frequently Asked Questions
- What is Selenium in Java used for?
- Why is Selenium with Java considered the best?
- Which is better: Selenium with Java or Python?
- Is Java knowledge required for Selenium?
- What is Selenium Java architecture?
- How to implement Page Object Model (POM) in Selenium Java?
- How can I write a network path in Selenium Java?
- How to verify text in Selenium WebDriver with Java?
Selenium with Java Tutorial: As the digital landscape continues to evolve rapidly, ensuring that your software is of high quality is crucial for the success of your product. That’s where automation testing comes in – it can help you test your software faster, more efficiently, and with greater accuracy than manual testing.
Selenium, the popular open-source tool that automates web browsers, is a game-changer for web-based automation testing. And, when it comes to leveraging Selenium, Java is a widely used programming language for automation testing. This Selenium with Java tutorial helps you learn end-to-end automation using Java Selenium testing tools
In this tutorial, we’ll take you on a journey of learning how to use Selenium with Java to automate your testing process and deliver top-notch software to your end users. We’ll provide you with valuable insights and hands-on experience in automation testing, so you can confidently create high-quality software that meets your customers’ needs.
So, if you’re looking to upgrade your automation testing skills and add Selenium with Java to your testing arsenal, this tutorial is the perfect resource for you. Let’s get started!/*
What is Selenium with Java?
Selenium is a powerful open-source testing framework that is widely used for automating web-based applications. It is a suite of tools that allows developers and testers to write and execute test cases against web applications in various programming languages, including Java, Python, C#, and Ruby.
Selenium’s key feature is the Selenium WebDriver, which is a browser automation API that provides a simple and concise programming interface for interacting with web browsers. It supports various browsers such as Google Chrome, Mozilla Firefox, Microsoft Edge, and more, making it an incredibly versatile tool for web automation testing.
Selenium WebDriver enables users to interact with web elements, such as text fields, buttons, and links, and perform various actions, including clicking, typing, and selecting. It also supports various types of waits that help to ensure the stability of the test scripts.
Additionally, Selenium provides an integrated development environment (IDE) that allows users to record and playback their test scripts. It also supports various reporting tools that enable users to analyze test results and identify issues.
Why Use Selenium with Java for Automation Testing
Developers often learn Selenium with Java because it offers a powerful combination of a widely used programming language and an industry-standard testing framework. Java is a popular language for automation testing because of its robustness, flexibility, and platform independence.
Additionally, Java’s object-oriented programming model makes it easy to write reusable and maintainable Selenium Java scripts.
Selenium, on the other hand, enables the creation of efficient and reliable test scripts for web-based applications. Selenium WebDriver provides a concise programming interface for interacting with web browsers, and it supports various programming languages, including Java.
Some of the key benefits of learning Selenium with Java include the following:
- Wide Industry Adoption: Java and Selenium are widely used in the industry for automation testing, and most companies prefer developers with expertise in these tools. Learning Java with Selenium can open up opportunities for developers in various industries and organizations.
- Flexibility: Java’s object-oriented programming model and Selenium’s flexible API allow developers to create test scripts that are reusable and maintainable. Test scripts written in Java with Selenium can be integrated with other tools and frameworks, making it a highly versatile solution.
Developers looking to learn Selenium with Java benefit from its simplicity and wide tooling support, making it ideal for both beginners and experts in Selenium automation testing.
How Selenium WebDriver Works
This section of the Java Selenium tutorial explains how WebDriver interacts with browsers using the JSON Wire Protocol.
The four basic components of WebDriver Architecture include:
- Selenium client Libraries
- JSON Wire Protocol over HTTP
- Browser Drivers
- Browsers

1. Selenium client Libraries
Selenium developers have developed language bindings/ Client Libraries in order to support multiple languages. There are bindings available for each language, like Java, C#, Python, Ruby, PHP, etc. Any tester who has a basic knowledge of working with any programming language can get specific language bindings and start off.
2. JSON Wire Protocol over HTTP
JSON Wire Protocol handles all the communication between the browser and the code. JSON is an open standard for data exchange on the web, and it supports data structures like objects and arrays. So it becomes easy to write and read data from JSON. Data is transferred using a RESTful (Representational State Transfer) API using JSON over HTTP.
3. Browser Drivers
Each browser (supported by Selenium) has its own implementation of the W3C standard that Selenium provides; each browser has its own separate browser driver (browser binaries). Drivers communicate with the respective browser, and it hides the implementation logic from the end user. JSON Wire Protocol makes a connection between the browser binaries and the client libraries.
4. Browsers
There are multiple browsers supported by Selenium, which are Firefox, Internet Explorer, Chrome, Opera, Safari, etc.
What happens in the background when the user executes the Selenium code?
Selenium WebDriver gives you an API that will give you access to methods like sendKeys(), getTitle(), findElement(), etc.
Below are the actions that happen in the background
- For each Selenium command, there is an individual HTTP request generated (every command in your script will be converted into a URL), and it is passed to the respective browser driver.
- The browser driver receives the request through an HTTP server.
E.g., the Client makes HTTP POST requests to the browser driver. findElement and click() are sent as a POST request to the browser driver from the Client.
- The HTTP server decides which actions need to be executed on the real browser.
- The browser follows the instructions as decided in the previous step and executes them.
- The HTTP server receives the execution status and then sends back the status to an automation script, which actually shows the result as either passed, failed, or error, etc.
Master Web Automation with Selenium WebDriver – Explore this in-depth guide.
How to Use Selenium with Java for Web Automation Testing
If you’re exploring Selenium automation testing with Java, this step-by-step guide walks you through setup and execution.
To use the Selenium with Java Tutorial, we need to follow these steps:
Step 1: Install JDK
- Download the latest version of JDK from Oracle’s website
- Install the downloaded JDK package on your machine.
- Locate the downloaded file (it should be an .exe file) and double-click on it to begin the installation process.
- Follow the on-screen instructions to complete the installation. You will need to specify the installation directory, so choose a location on your computer where you want the JDK to be installed.
- Once the installation is complete, you will need to set the JAVA_HOME environment variable.
To set up the environment variables for Java on your system, follow these steps:
- To do this, click on the Start menu and type “Environment Variables” in the search bar. Then click on “Edit the system environment variables”.

- Under the “Advanced” tab, click on “Environment Variables” at the bottom of the window.

- Locate the path where the Java Development Kit (JDK) is installed, which will typically be something like “C:\Program Files\Java\jdk-19\bin”.
- In the ‘Environment Variables’ window that opens, select the ‘New’ button under the ‘System variables’ section

- Set the path to the JDK installation by entering it in the ‘Variable value’ field. If the ‘Path’ variable already exists, edit it by adding the JDK path at the end of the existing value, separated by a semicolon (;).

- To set the CLASSPATH variable, create a new environment variable named ‘CLASSPATH’ and set its value to the same JDK path used in step 4. If the ‘CLASSPATH’ variable already exists, edit it by adding the JDK path at the end of the existing value, separated by a semicolon (;).

Once you have completed these steps, the environment variables for Java on your system should be set up correctly. To verify that Java has been successfully installed, open the command prompt and run the following command:
java -version

If Java is installed correctly, the command will display the version number of the installed Java Development Kit.
Step 2: Download the Selenium Java Client Driver
- Go to the Selenium official website and download the Java version of the Selenium Client Driver.

- Extract the downloaded archive file.

Step 3: Set Up Eclipse IDE
- Go to the official website and download the Eclipse installer from the website.

2. Choose ‘Eclipse IDE for Java Developers’.

3. Now, click on the ‘Install’ button, and your download should start.

4. Once your download is complete, launch the IDE.

5. Launch the IDE and create a new Java project.
Step 4: Add Selenium Dependencies (Classpath or Maven)
- Right-click on your project in the Project Explorer view in Eclipse, and select “Properties” from the context menu.
- In the Properties dialog box, select “Java Build Path” from the left pane.
- Click on the “Libraries” tab.

- Click on the “Add External JARs” button and select the Selenium Java Client Driver JAR file that you downloaded in Step 2.
- Open the client-combined JAR file by clicking on it once and then clicking the “Open” button.

6. Next, go to the folder where the other JARs you want to add are located. This folder is usually called “libs”. Select all the JAR files in the “libs” folder by holding down the “Ctrl” key on your keyboard and clicking on each file. Click the “Open” button to add all the selected JAR files to your project.

7. Once you have added all the JARs you need, click the “Apply and Close” button to save the changes and close the window.

Remember to make sure that the JARs you add are compatible with your project’s version of Java, and that they do not conflict with any existing JARs in your project.
Step 5: Create a Selenium Maven Project in Eclipse
To create a Selenium with Java project using Maven in Eclipse, follow these steps:
Step 1: Launch Eclipse IDE and create a new workspace.
Step 2: Create a new Maven project by going to File > New > Other > Maven > Maven Project.
Step 3: In the New Maven Project wizard, select the “Create a simple project” checkbox and click on “Next.”
Step 4: In the “New Maven Project” wizard, fill in the Group Id and Artifact Id fields as per your project requirements and click on “Finish.”
Step 5: Right-click on the project name in the “Package Explorer” view and select “New” > “Package” to create a new package.
Step 6: Name the package as per your requirements and click “Finish.”
Step 7: Right-click on the newly created package and select “New” > “Java Class.”
Step 8: Name the Java class as per your requirements and click “Finish.”
Step 9: Open the pom.xml file in your project. If it doesn’t already have a dependencies section, add one within the tags:
<dependencies>
<!-- Dependencies will be listed here -->
</dependencies>
Step 10: Add the Selenium Java Client Driver dependency inside the tags:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.1.0</version>
</dependency>
This specifies the Selenium Java Client Driver dependency with a group ID of org.seleniumhq.selenium, an artifact ID of selenium-java, and a version of 4.1.0.
Note: You can replace the version number with the latest version of Selenium available.
Step 11: Save the pom.xml file, then right-click on the project and select “Maven” > “Update Project.”
Step 12: In the “Update Maven Project” dialog box, check the “Force Update of Snapshots/Releases” option and click “OK.”
Maven will automatically download and manage the required dependencies for your project, including the Selenium Java Client Driver. This approach is much easier and more efficient than manually adding JAR files to your project.
You are now ready to start writing your Selenium with Java tests.
Write Your First Selenium Test in Java with Eclipse IDE
To write Selenium with Java code in Eclipse IDE, follow these steps:
Step 1: Launch Eclipse IDE and open the Selenium Java project.
Step 2: Create a new package by right-clicking on the src folder in the Project Explorer view and selecting “New” > “Package.”
Step 3: Name the package and click “Finish.”
Step 4: Create a new Java class in the package by right-clicking on the package and selecting “New” > “Class.”
Step 5: Name the class and click “Finish.”
Step 6: Import the necessary Selenium and Java packages by adding the following import statements at the beginning of your class:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
Step 7: Set the system property for the ChromeDriver executable by adding the following code before creating an instance of the WebDriver interface:
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");
Replace “path/to/chromedriver.exe” with the actual path to the ChromeDriver executable on your machine.
Note: If you’re using Selenium 4.6 or later, you can often skip this manual step entirely. Newer Selenium versions ship with Selenium Manager, a built-in utility that automatically detects the browser installed on your machine and downloads the matching driver for you. In that case, your code simplifies to:
WebDriver driver = new ChromeDriver();
Selenium handles locating and configuring the correct ChromeDriver binary in the background. The manual System.setProperty() approach above is still worth knowing, though it’s useful when you need to pin a specific driver version, work in an offline or restricted environment, or troubleshoot a driver-browser version mismatch. For most everyday projects on Selenium 4.6+, however, letting Selenium Manager handle it is the simpler and less error-prone option.”
Step 8: Inside the main method of the class, create an instance of the WebDriver interface using the ChromeDriver class and navigate to a URL:
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
}
Step 9: Save the file and run it by right-clicking on the class and selecting “Run As” > “Java Application.”
Congratulations! You have just written your first Selenium with Java code in Eclipse IDE. You can now explore further and add more code to automate web testing.
Handling Alerts, Frames, and Multiple Windows/Tabs
Once you’re comfortable navigating a single page, the next step is learning to handle the browser behaviors that show up constantly in real test scenarios: pop-up alerts, embedded frames, and multiple browser windows or tabs.
Handling Alerts
JavaScript alerts (confirmation boxes, prompts, and simple pop-ups) pause script execution until dismissed. Selenium provides a dedicated Alert interface to interact with them:
import org.openqa.selenium.Alert;
Alert alert = driver.switchTo().alert();
alert.accept(); // Clicks 'OK'
alert.dismiss(); // Clicks 'Cancel'
String alertText = alert.getText(); // Reads the alert message
Handling Frames
Some pages embed one HTML document inside another using frames or iframes. WebDriver treats the main page and each frame as a separate context, so you need to explicitly switch into a frame before interacting with elements inside it, then switch back out:
driver.switchTo().frame("frameName"); // Switch by name or ID
driver.switchTo().frame(0); // Switch by index
driver.switchTo().defaultContent(); // Return to the main page
Handling Multiple Windows and Tabs
Actions like clicking a link that opens a new tab, or a third-party login popup, spawn a new window that Selenium doesn’t automatically switch to. You can loop through the open window handles and switch to the one you need:
String parentWindow = driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) {
driver.switchTo().window(handle);
// interact with the new window here
}
driver.switchTo().window(parentWindow); // Switch back once done
Getting comfortable with alerts, frames, and window handles early on will save you a lot of ‘element not found’ errors later, since a large share of those failures simply come from WebDriver looking in the wrong browsing context.
Introduction to TestNG Framework
Together with Selenium WebDriver, TestNG enhances your Java Selenium automation workflow by supporting flexible test management and execution.
TestNG is a widely used testing framework for Java that is highly preferred by developers for automated testing. It provides advanced features and functionalities that make it an excellent choice for unit, integration, and end-to-end testing.
TestNG extends the capabilities of JUnit and offers additional functionalities such as flexible test configuration, support for data-driven testing, parallel test execution, and test reporting. The name TestNG stands for ‘Test Next Generation’, which indicates the framework’s ability to handle modern testing challenges and provide solutions that align with modern software development practices.
The framework’s flexible test configuration allows developers to define and configure tests based on their requirements, making it easy to manage and organize tests. TestNG also supports data-driven testing, which is a powerful technique that enables developers to test the same code with different sets of data, thereby minimizing redundancy and improving test coverage.
TestNG’s parallel test execution feature allows developers to execute tests concurrently, reducing test execution time and improving overall test efficiency. Additionally, TestNG provides a detailed test report that includes information about test failures, skipped tests, and test execution time, allowing developers to identify and debug issues easily.
Using the TestNG framework for parallel test execution
When working on an actual project, running and maintaining hundreds of test cases is necessary to ensure product quality before going live. Executing test cases on multiple platforms and devices is also crucial to ensure that the application behaves as expected under various conditions. However, the overall test execution time can become lengthy, making it highly desirable to reduce it. One way to achieve this is through parallel testing.
Parallel testing is a preferred test execution strategy where tests are run in parallel to reduce the overall test execution time. This approach replaces the traditional method of sequential testing, which can be time-consuming.
TestNG is a popular testing framework that supports parallel testing out of the box. To run tests in parallel, you need to configure the TestNG XML file to specify the test classes and the number of threads to be used for parallel execution. Additionally, you can use a cloud-based Selenium Grid service to run tests on multiple browsers and operating systems simultaneously.
Parallel Test execution in TestNG using TestNG XML file
One of the key advantages of TestNG is its support for parallel test execution. This is achieved through the utilization of the Multi-Threading concept of Java, which allows multiple threads to execute simultaneously without any dependence on each other.
To enable parallel testing, we need to make the required changes in the TestNG XML file. The parallel attribute is used to trigger parallel execution and accepts four values: classes, methods, tests, and instances. Developers can also set the number of threads they wish to allocate during execution using the thread-count attribute.
Step-by-Step Guide to Install TestNG Plugin in Eclipse from “Eclipse Marketplace“
If you’re wondering how to install TestNG in Eclipse, don’t worry; it’s a straightforward process that can be easily accomplished by following these steps:
Step 1) Launch Eclipse and click on the Help option on the menu bar. From there, choose “Eclipse Marketplace” to begin the installation process.

Step 2) In the Install pop-up window, use the “Find” option to search for TestNG. Once you’ve found it, click on the installation button to proceed.

Step 3) After selecting TestNG, you’ll be prompted to confirm the installation process. Click on the “Confirm” button to continue.

Step 4) Next, you’ll need to accept the license agreement. This involves selecting the “I accept the terms of the license agreement” radio button and then clicking on “Finish”. Depending on your internet speed, this step may take some time.

Step 5) After accepting the license agreement, the TestNG installation process will begin. You’ll need to wait for it to complete before moving on to the next step.

Step 6) If a security warning appears during the installation process, don’t worry – just click on “Install Anyway” to proceed.

Step 7) Once the installation is finished, Eclipse will prompt you to restart your system. Click on “Restart now” to complete the installation process.

Step 8) After your system has restarted, you’ll need to verify that TestNG for Eclipse was successfully installed. To do this, click on Window > Show View > Other, then navigate to the Java directory and look for TestNG. If it’s there, then congratulations – you’ve successfully installed TestNG in Eclipse!


With TestNG successfully installed and a TestNG project created, you are now ready to write and run your first TestNG test.
How to run test cases in parallel with Selenium in TestNG on Cloud Grid?
To run tests in parallel with Selenium in TestNG on a cloud grid, we need to follow the below-mentioned steps.
Step 1: Go to the TestNG project that we created.
Step 2: Create a new TestNG class file by following these steps:
- Right-click on the project source folder and select TestNG towards the bottom of the list.
- Select ‘Create TestNG Class’.
- Name your class; choose the required annotations; provide the XML file name, and click Finish.
The TestNG class file is created.
Step 3: Configure the TestNG XML file to run in parallel mode. The steps are as follows:
- Open the testng.xml file. If it is not already created, create the file by adding a new file to the project and name it testng.xml.
- Edit the boilerplate code. You can name the test suite and name as you like. But the class name should be exactly that of our TestNG class.
- To start parallel test execution in TestNG, provide the ‘parallel’ attribute to <suite>. For parallel execution of the test methods, set the attribute value to “tests”
- To run automated tests with Selenium on a cloud grid, it is essential to configure the tests to run on specific browsers, browser versions, and operating systems. This configuration ensures that the tests run consistently and accurately across various platforms, improving the overall quality of the product.
To set up the test case to run on a specific browser, browser version, and OS, parameters need to be added to the TestNG XML file.
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Example Test Suite" parallel="tests" thread-count="3">
<test name="Example Test">
<parameter name="browser" value="chrome" />
<parameter name="browser_version" value="latest" />
<parameter name="os" value="Windows 10" />
<classes>
<class name="com.example.TestNGExample" />
</classes>
</test>
</suite>
Yes, you are correct. The above code is just a snippet of the TestNG XML file with parameters for browser, browser version, and OS. Here is an example Java code snippet that shows how to use these parameters in a Selenium test:
public class TestNGExample {
WebDriver driver;
@Parameters({"browser", "browser_version", "os", "hub_url"})
@BeforeTest
public void setup(String browser, String browserVersion, String os, String hubUrl) throws MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browserName", browser);
caps.setCapability("browserVersion", browserVersion);
caps.setCapability("platform", os);
// initialize RemoteWebDriver based on the specified browser, browser version, and OS
// example for Chrome browser
if(browser.equalsIgnoreCase("chrome")) {
ChromeOptions options = new ChromeOptions();
options.merge(caps);
driver = new RemoteWebDriver(new URL(hubUrl), options);
}
// other browser options can be added similarly
}
@Test
public void testExample1() {
// your Selenium test code for test example 1 goes here
}
@Test
public void testExample2() {
// your Selenium test code for test example 2 goes here
}
@Test
public void testExample3() {
// your Selenium test code for test example 3 goes here
}
@AfterTest
public void teardown() {
driver.quit();
}
}
- Finally, it is time to run your test case. Right-click on yourtestng.xml file and navigate to Run As > TestNG Test Suite.
By following these steps, we can run our TestNG test cases in parallel mode with Selenium on a cloud grid, enabling faster execution and efficient utilization of resources.
Conclusion
In this tutorial, we covered the basics of Selenium with Java and TestNG, starting from setting up the environment to executing test cases. We also learned about how to perform mouse and keyboard actions using Selenium.
In conclusion, Selenium with Java is a powerful combination that can help us perform automated testing on web applications quickly and efficiently. By following the steps and best practices covered in this Selenium with Java tutorial, we can write reliable and robust Selenium scripts that can help us find bugs and issues in web applications, ultimately leading to a better user experience for our customers.
Frequently Asked Questions
What is Selenium in Java used for?
Selenium in Java is used to automate web browser actions for testing web applications. It helps you create and run test cases in Java, making web automation faster and more reliable.
Why is Selenium with Java considered the best?
Selenium with Java is popular because of Java’s large community, platform independence, and rich ecosystem of frameworks and libraries. With tools like TestNG, JUnit, and IDE support, it saves time, reduces errors, and gives access to vast community knowledge.
Which is better: Selenium with Java or Python?
It depends on your project needs.
– Java offers a strong ecosystem (TestNG, JUnit) and is statically typed for strict compile-time checks.
– Python is simpler, dynamically typed, and has frameworks like PyTest, Robot Framework, and SeleniumBase.
Choose based on whether you prefer strict typing and scalability (Java) or simplicity and flexibility (Python).
Is Java knowledge required for Selenium?
No, Java is not mandatory. Selenium supports multiple languages like Python, C#, and JavaScript. However, Java is widely used and beginner-friendly for Selenium automation, making it a good starting point.
What is Selenium Java architecture?
Selenium Java architecture is the framework design that enables browser automation using Java. It combines components like WebDriver, language bindings, and browser drivers to execute automated tests.
How to implement Page Object Model (POM) in Selenium Java?
To implement POM in Selenium Java:
1. Create a Java class for each page.
2. Define page elements as private variables.
3. Add public methods for actions on the page.
4. Use a separate test class to call these methods.
This separates test logic from page logic, making tests easier to maintain.
How can I write a network path in Selenium Java?
Use forward slashes (/) instead of backslashes (\) in network paths. Backslashes act as escape characters in Java, which can cause errors. Forward slashes ensure paths work correctly in Selenium scripts.
How to verify text in Selenium WebDriver with Java?
You can verify text using:
1. getText() method to capture element text.
2. Conditional statements (if/else) or Assert methods (TestNG/JUnit) to compare actual vs expected text.