Selenium with Java for Web Automation: The Complete Guide

James CantorJames Cantor
18 min read

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, 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:

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

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

selenium web driver arctiture

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

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

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

  1. The HTTP server decides which actions need to execute on the real browser.

  2. The browser follows the instructions as decided in the previous step and executes them.

  3. 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 withSelenium 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

  1. Download the latest version of JDK from Oracle’s website

  2. Install the downloaded JDK package on your machine.

  3. Locate the downloaded file (it should be a .exe file) and double-click on it to begin the installation process.

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

  5. 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:

  1. To do this, click on the Start menu and type “Environment Variables” in the search bar. Then click on “Edit the system environment variables”.

selenium web driver arctiture1

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

selenium web driver arctitur2

  1. Locate the path where the Java Development Kit (JDK) is installed, which will typically be something like “C:\Program Files\Java\jdk-19\bin”.

  2. In the ‘Environment Variables’ window that opens, select the ‘New’ button under the ‘System variables’ section.

selenium web driver arctitur3

  1. 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 (;).

selenium web driver arctitur4

  1. 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 (;).

selenium web driver arctitur5

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

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

  1. Go to the Selenium official website and download the Java version of the Selenium Client Driver.

selenium official website

  1. Extract the downloaded archive file.

extract selenium

Step 3: Set up Eclipse IDE for java Developers

  1. Go to the official website and download the Eclipse installer from the website.

eclipse

2. Choose ‘Eclipse IDE for Java Developers’.

eclipse ide developer

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

install eclipse

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

launch eclipse 1

5. Launch the IDE and create a new Java project.

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

  1. Right-click on your project in the Project Explorer view in Eclipse, and select “Properties” from the context menu.

  2. In the Properties dialog box, select “Java Build Path” from the left pane.

  3. Click on the “Libraries” tab.

java build path

  1. Click on the “Add External JARs” button and select the Selenium Java Client Driver JAR file that you downloaded in Step 2.

  2. Open the client-combined jar file by clicking on it once and then clicking the “Open” button.

java build path1

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.

java build path libs

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

java build path libs1

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:

  1. Open your project in Eclipse and locate the “pom.xml” file.

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

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

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

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

  1. Save the changes to your “pom.xml” file.

  2. Right-click on your project and select “Maven” > “Update Project”.

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

Eclipse Marketplace screenshot

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.

image 34

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

image 34

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.

image 37

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.

image 35

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

image 38

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

image 39

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!

image 40

image 41

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:

  1. Right-click on the project source folder and select TestNG towards the bottom of the list.

  2. Select ‘Create TestNG Class’.

  3. 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:

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

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

  3. 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.”

  4. 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();

}

}

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

0
Subscribe to my newsletter

Read articles from James Cantor directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

James Cantor
James Cantor

For over 6 years, I've been obsessed with building rock-solid tech experiences. I'm like a detective, uncovering hidden bugs and fixing them before they cause trouble. But my passion doesn't stop there! I love sharing my knowledge through my blog, sparking discussions and helping others grow in the tech world.