Selenium with Java for Web Automation: The Complete Guide
Tags: selenium, automation, web, javatutorial
Published: 2024-02-26 14:12:18

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 that offers robust support for automation testing.

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!

## Selenium with Java Tutorial: Selenium Automation Testing with Java

Selenium automation testing with Java is a powerful combination that enables the creation of efficient and reliable test scripts for web-based applications. In this guide, we will provide a step-by-step approach to getting started with Selenium automation testing using Java.

**What is Selenium?**

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](https://testgrid.io/blog/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 do Developers learn Selenium with Java?**

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.

**How does Selenium WebDriver work?**

The four basic components of WebDriver Architecture include:

1. Selenium client Libraries
2. JSON Wire Protocol over HTTP
3. Browser Drivers
4. 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 does 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 as a URL), and it is passed to the respective browser driver.
- The browser driver receives the request through an HTTP server.

For e.g., the Client makes HTTP POST requests to the browser driver. findElement, click() are sent as a POST request to the browser driver from the Client.

- The HTTP server decides which actions need to execute 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?**
 

To use Selenium with Java Tutorial, we need to follow these steps:

1. Download and install Java Development Kit (JDK) on your machine.
2. Download the Selenium Java Client Driver from the official Selenium website.
3. Set up an Integrated Development Environment (IDE) like Eclipse or IntelliJ
4. Create a Java project in your IDE.
5. Add the Selenium Java Client Driver to your project’s classpath.
6. Write your Selenium test code using Java.
7. Run your test code.

Here are the detailed steps:

**Step 1: Download and 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 a .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
 

- 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 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 for java Developers**

- Go to the official website and download the Eclipse installer from the website.
- Choose ‘Eclipse IDE for Java Developers’.
- Now, Click on the ‘Install’ button and your download should start.
- Once your download is complete, launch the IDE.
- Launch the IDE and create a new Java project.


**Step 4.1: Add Selenium Java Client Driver to the project’s classpath**

- 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 
- Open the client-combined jar file by clicking on it once and then clicking the “Open” button.
- 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.

- 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 4.2: Create a Selenium with Java project using Maven 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 “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: Save the changes to the pom.xml file and update the project’s dependencies by right-clicking on the project name and selecting “Maven” > “Update Project.”
Step 10: You are now ready to start writing your Selenium with Java tests.

**Step 4.3: Add Selenium Java Client Driver to a Maven Project using Dependencies.**

Using Maven, adding dependencies to your project is a much more modern approach for managing libraries, instead of manually adding JAR files. To add the Selenium Java Client Driver to your Maven project, follow these steps:
Open your project in Eclipse and locate the “pom.xml” file.
If you don’t have a dependencies section in your pom.xml file, you’ll need to create one. This section will contain all the dependencies for your project. Add the following code within the <project> tags:
<dependencies>
  <!– Dependencies will be listed here –>
</dependencies>

Now you can add the Selenium Java Client Driver dependency to the dependencies section. To do this, add the following code within the <dependencies> tags:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.1.0</version>
</dependency>

This code 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.

Save the pom.xml file and refresh the project. The dependency should now be added to your project.

Note: You can replace the version number with the latest version of Selenium available.
Save the changes to your “pom.xml” file.
Right-click on your project and select “Maven” > “Update Project”.

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.

**How to write selenium-java code 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.
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.

## Introduction to the TestNG framework

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 the 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 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 however, 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 as “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 your testng.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 action 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.
This blog is originally published at [Testgrid](https://testgrid.io/blog/selenium-with-java-tutorial/)