Click here to Skip to main content
15,892,298 members
Articles / Programming Languages / Java
Article

Running Automation Tests at Scale Using Java

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
9 Nov 2023CPOL11 min read 4.3K   1
This post will discuss Selenium, how to set it up, and how to use Java to create an automated test script.

This article is a sponsored article. Articles such as these are intended to provide you with information on products and services that we consider useful and of value to developers

The Internet is widely accessible, and web and mobile platforms strongly influence consumer purchasing decisions. As a result, many companies are working to give their customers a high-quality digital experience. Simply said, a lot of web and mobile apps are being created globally and digital presence has become one of the critical priorities for every business. According to Netcraft’s June 2023 Web Server Survey, there are currently more than 1.106 billion websites on the Internet.

Image 1

As customer decision making is now highly dependent on digital experience as well, organisations are increasingly investing in quality of that digital experience. That means establishing high internal QA standards and most importantly investing in Automation Testing for faster release cycles.

So, how does this concern you as a developer or tester? Having automation skills on your resume is highly desirable in the current employment market. Additionally, getting started is quick. Selenium is the ideal framework for beginning automation testing. It is the most popular automated testing framework and supports all programming languages.

This post will discuss Selenium, how to set it up, and how to use Java to create an automated test script. Next, we will see how to use a java based testing framework like TestNG with Selenium and perform parallel test execution at scale on the cloud using LambdaTest.

Table of Contents

What is Selenium?

Selenium is a popular framework for automated testing of web applications. 64.2% of respondents to a recent poll on test automation claimed they used Selenium to automate testing.

Image 2

Selenium offers browser testing on all modern web browsers, such as Google Chrome, Mozilla Firefox, Microsoft Edge, Safari, and more. The platforms supported by Selenium include Linux, Windows, MacOS, and Solaris. Automation test scripts can be written in various programming languages, such as Python, C#, Java, JavaScript(Node.js), Ruby, and more, allowing testers to automate their website testing in the most comfortable language.

Selenium framework mainly comprises three components. All these components can be operated individually or paired with one other to achieve a greater deal.

Image 3

Selenium IDE

Selenium IDE (Integrated Development Environment) provides a friendly user interface that allows developers and testers to record and play test scripts. Selenium IDE can be used to generate test scripts based on actions performed on a browser.

Selenium WebDriver

Selenium WebDriver is one of the most critical components of the Selenium suite for overall browser-based automation testing. WebDriver is a remote control interface component that permits the automation script to interact with browsers, manipulate DOM elements, and manage the user agent's action. In a nutshell, WebDriver is a bridge between Selenium and the browser over which the test cases run.

Selenium Grid

Selenium Grid is primarily used to execute parallel tests on devices against multiple supported browsers. Since almost all popular browsers and operating systems are supported by Selenium, it is more straightforward for the Selenium Grid to execute numerous tests simultaneously on various operating systems with various browsers.

How to Setup Selenium with Java?

Before writing our first automation testing script in Selenium Java, we must set up Selenium with Java on our system.

Prerequisites:

  • Java Development Kit (JDK) installed on the system.
  • Any modern web browser like Chrome or Firefox.
  • Your favorite IDE. In our case, we use Eclipse.

Now, let us guide you through the integration process step by step.

  1. From Selenium's official website, download the Selenium Client and WebDriver Language Bindings. Here, you can choose the Java language bindings for our needs. This will download a ZIP file containing the WebDriver JAR files.

    Image 4

  2. Now open the Eclipse IDE and create a New Project by navigating to File > New > Java Project, as shown in the image below, and give a desired name to the project.

    Image 5

  3. Now that your project is created, create a package by right-clicking on the project, selecting File > New > Package, and giving a desired package name. (Optional)

    Image 6

  4. Similarly, you can create a new Java class by navigating to File > New > Class.
  5. In the final step, we must import the extracted WebDriver file downloaded from the Selenium website. To add, right-click on the project name and go to Build Path > Configure Build Path. Next, Click on the Add External JARs button and locate the downloaded JAR files. Finally, click on the Apply and Close button to save the changes.

    Image 7

Writing First Automation Test Script with Selenium

It's time to get hands-on experience writing an automation test script in Java using Selenium. We will look at a simple and familiar example of a Todo list web app for this.

In this section, we are going to create two examples. Starting with a fundamental one to "Open a web page and print its title," we will also cover a little complex example to "add an item in the Todo list."

Example 1: Open a web page and print its title

In this example, we will write an automation test script to open the same Todo list website in the Chrome browser using Selenium with Java. Once the website is loaded completely, we will print the title of the website.

Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class FirstProject {
    public static void main(String[] args) {

        // No need for setProperty as ChromeDriver() will auto install
        // required browser driver for Chrome using Selenium Manager
        WebDriver driver = new ChromeDriver();

        // Open the "https://lambdatest.github.io/sample-todo-app/" web 
        // page on the browser
        driver.get("https://lambdatest.github.io/sample-todo-app/");

        // Add time Delay for complete page load
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // Catch block to handle the exception
            e.printStackTrace();
        }

        // Print the tile of the current tab
        System.out.println(driver.getTitle());

        // Close the current browser session
        driver.quit();
    }
}

Image 8

Console Output

Image 9

Code Walkthrough

The first thing we do is import all the necessary packages for performing the test. WebDriver class from the Selenium Java library for automating browser actions and ChromeDriver class for creating an instance of WebDriver for Chrome using Selenium manager.

Image 10

Next, we initialize the WebDriver for the Chrome browser using the ChromeDriver() method.

Image 11

Once we finish the initialization, we move to our primary goal of opening the web page in the Chrome browser. Here, we use the get() method of the WebDriver object, which is used to navigate to a specific URL. It instructs the web browser to open the specified URL.

Image 12

Finally, we print the web page's title opened using the getTitle() method provided by the WebDriver object, which returns the current page's title opened in the browser session.

Image 13

After all the test objectives are achieved, it's time to close the browser session and free the system’s memory.

Image 14

Example 2: Add a Todo list

Now, we will explore a little interactive example of adding an item "New todo task added" to our Todo list. We will use the Mozilla Firefox browser to perform automation tasks here. So, let’s jump on to the code and understand it.

Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;


public class CloseCurrentTab {
    public static void main(String[] args) {
       
        // No need for setProperty as ChromeDriver() will auto install
        // required browser driver for Chrome using Selenium Manager
        WebDriver driver = new FirefoxDriver();
       
       // Open the "https://lambdatest.github.io/sample-todo-app/" 
 // web page on the browser
        driver.get("https://lambdatest.github.io/sample-todo-app/");
       
        // Find the input field element by its 'id'.
        WebElement inputbar = driver.findElement(By.id("sampletodotext"));

        // Enter text into the input field.
        inputbar.sendKeys("New todo task added");

        // Find the submit button element by its 'id'.
        WebElement submitBtn = driver.findElement(By.id("addbutton"));

        // Click the submit button.
        submitBtn.click();

        // Add a time delay (5 seconds) for visibility and observability.
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // Catch block to handle the exception 
      // (e.g., if sleep is interrupted).
            e.printStackTrace();
        }
   
        // Close the current browser session
        driver.quit();
    }
}

Image 15

Output

Image 16

Code Walkthrough

In this example, we must import the WebElement and By class to select elements on the web page for interaction.

Image 17

Then we initialize the Firefox browser using the below code.

Image 18

Next, we open the Todo app, and the first thing we do is to find the Input bar on the website. We used findElement() method of WedDriver and By.id() method to select the unique ID of the element.

Image 19

Then, we can type the Todo list to add using sendKeys() method of the WebElement object, which sends a string to any field, like the input field of a form.

Image 20

Next, we should select the submit button using the WebElement class.

Image 21

Finally, we can click on the add button using click() method provided by the WebElement class to add our Todo item to the list.

Image 22

Importance of Test Automation Framework

Everyone knows that an appropriate automation testing script should start the browser, carry out the action, provide the data, interact as instructed, evaluate the results, and terminate. Yes, that is a big task! It might occasionally be difficult to write the ideal script.

Test Automation Framework can make this task easier because it provides methodical techniques to automate, manage, and arrange tests. The automation framework makes it simpler to identify and debug the coding issue.

Automation frameworks can significantly decrease time and effort if we create script components only once and make them available for any other tests to use as required, i.e., it offers Reusability – create once, debug once, finalize once, and reuse many times.

One such test automation framework for Selenium in Java is TestNG. TestNG (here NG stands for ‘Next Generation’) is an open-source Unit test automation framework for Java that has gained tremendous popularity among automation testers and developers.

TestNG for Parallel Test Execution

JUnit, another famous unit testing framework for the Java ecosystem, inspires the TestNG framework. However, it provides various distinctive and advanced features, making it much more robust than its peers. One such notable feature is its seamless support for Parallel Testing.

TestNG uses multithreading in Java, where we can define the number of threads we want to create for parallel execution. Based on this number, multiple threads are created, each running a separate test in parallel. It offers an auto-defined XML file where we can set the parallel testing attribute to classes/methods/tests.

Before using this TestNG framework in code, we must integrate it with our project by following steps:

  1. First, navigate to Eclipse Marketplace and install the TestNG plugin. Once installed, you can find it under the Installed section.

    Image 23

  2. Next, add the TestNG library to your project. To do so, navigate to Build Path > Configure Build Path. Next, Click on the Add Library button and choose the TestNG library.

    Image 24

Now that we have integrated TestNG into the project let’s create the first parallel test execution script.

Java
import org.openqa.selenium.By;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
 
public class TestMethodParallelExecution {

    @Test
    void openAndPrintTitle() {
        WebDriver driver = new FirefoxDriver();

        // Open the "https://lambdatest.github.io/sample-todo-app/" web
        // page on the browser
        driver.get("https://lambdatest.github.io/sample-todo-app/");


        // Add time Delay for complete page load
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // Catch block to handle the exception
            e.printStackTrace();
        }


        // Print the tile of the current tab
        System.out.println(driver.getTitle());


    }
 
    @Test
    void addNewTodoItem () {
        WebDriver driver = new FirefoxDriver();
       
        // Open the "https://lambdatest.github.io/sample-todo-app/" web page on the browser
         driver.get("https://lambdatest.github.io/sample-todo-app/");
       
         // Find the input field element by its 'id'.
         WebElement inputbar = driver.findElement(By.id("sampletodotext"));

         // Enter text into the input field.
         inputbar.sendKeys("New todo task added");

         // Find the submit button element by its 'id'.
         WebElement submitBtn = driver.findElement(By.id("addbutton"));

         // Click the submit button.
         submitBtn.click();

         // Add a time delay (5 seconds) to allow for visibility and observability.
         try {
             Thread.sleep(5000);
         } catch (InterruptedException e) {
             // Catch block to handle the exception (e.g., if sleep is interrupted).
             e.printStackTrace();
         }
    }
 
    @AfterMethod
    public void tearDown() throws Exception {
        if (driver != null) {
                driver.quit();
        }
    }
}

TestNG configuration XML file

XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Parallel Test Suite" parallel="methods" thread-count="2">
 
    <test name="First Test">
        <classes>
            <class name="testng2.TestMethodParallelExecution" />
        </classes>
    </test>
    <!-- Test -->
</suite> <!-- Suite -->

Code Walkthrough

In the Java code, both the functions for the test are the same as the previous examples. The only addition here is the annotation.

@Test: This annotation tells Selenium that the function below is a test and needs to be executed.

@AfterTest: The function below this annotation is executed once all the tests are executed.

Next, in the TestNG configuration XML file, we defined the number of threads to be executed in parallel using the thread-count attribute of the suit tag.

Image 25

Challenges of Testing on the Local Grid

All automation tests were on our local system or grid. Is it possible to scale? For example, managing local infrastructure, ensuring the physical availability of devices, and installing various required versions of operating systems, browsers, and other supporting tools is a hell of a task and, on top of that, not cost-effective.

Thus, testing web apps on all majorly available browser versions, platforms, and hardware specifications is a nightmare. This negatively impacts our test coverage across various browsers and platforms and needs to be more stable.

We can overcome this problem by leveraging the Cloud-based testing tools available. These tools are advantageous as they enable us to test cross-browser on multiple platforms. Hence enabling a more scalable and improved test coverage as a whole. They allow parallel testing, quicker test execution, and improved test coverage.

One such cloud-based testing platform is LambdaTest. LambdaTest is an AI-powered test orchestration and execution platform that allows automation testing on 3000+ browsers, OS combinations, and an online Selenium Grid that we can integrate with our current test project via bare minimum changes. LambdaTest allows us to run tests on the Online Selenium Grid on various browser versions.

Running Test on a Cloud-Based Testing Grid

This section will run both tests discussed above on LambdaTest using Selenium as the testing framework. We will test on the MAC operating system with the latest Firefox browser.

Before running this Java test on LambdaTest, follow simple steps:

  1. Create a LambdaTest account and complete all the required processes.
  2. To get your credentials, go to your profile icon in the top right corner and navigate to Account Settings.

    Image 26

  3. Then go to Password & Security. You can find your Username and Access Key and save it for future use.

    Image 27

To run our code on the LambdaTest, you need to modify our test case. So here is the modified code.

Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
import java.net.MalformedURLException;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;

public class CloseCurrentTab {
    // Your LambdaTest secrets and urls
    String username = "YOUR USERNAME";
    String accesskey = "YOUR ACCESS KEY";
    static RemoteWebDriver driver = null;
    String gridURL = "@hub.lambdatest.com/wd/hub";
    boolean status = false;
   
    public static void main(String[] args) {
       new CloseCurrentTab().openAndPrintTitle();
       new CloseCurrentTab().addNewTodoItem();
       
    }
   
    private void setUp() {
        // Define Grid URL for LambdaTest Cloud Grid server
        URL finalGridURL = new URL("https://" + username + ":" + accesskey + gridURL)

        // Set Capabilities to help lambdatest understand you requirement
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("browserName", "Firefox");
        capabilities.setCapability("platformName", "macOS Ventura"); // If this cap isn't specified, it will just get any available one.
        capabilities.setCapability("build", "Testing Todo list example");
        capabilities.setCapability("name", "Open and Add a Todo");
        capabilities.setCapability("project", "LambdaTest Example");
        try {
            driver = new RemoteWebDriver(finalGridURL, capabilities);
        } catch (MalformedURLException e) {
            System.out.println("Invalid grid URL");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
   
    void openAndPrintTitle() {
        setUp();
        WebDriver driver = new FirefoxDriver();

        // Open the "https://lambdatest.github.io/sample-todo-app/" web
        // page on the browser
        driver.get("https://lambdatest.github.io/sample-todo-app/");
        // Add time Delay for complete page load
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // Catch block to handle the exception
            e.printStackTrace();
        }

        // Print the tile of the current tab
        System.out.println(driver.getTitle());

        // Close the current browser session
        driver.quit();

    }
   
    void addNewTodoItem () {
        setUp();
        WebDriver driver = new FirefoxDriver();
        // Open the "https://lambdatest.github.io/sample-todo-app/" web page on the browser
         driver.get("https://lambdatest.github.io/sample-todo-app/");
       
         // Find the input field element by its 'id'.
         WebElement inputbar = driver.findElement(By.id("sampletodotext"));

         // Enter text into the input field.
         inputbar.sendKeys("New todo task added");

         // Find the submit button element by its 'id'.
         WebElement submitBtn = driver.findElement(By.id("addbutton"));

         // Click the submit button.
         submitBtn.click();

         // Add a time delay (5 seconds) to allow for visibility and observability.
         try {
             Thread.sleep(5000);
         } catch (InterruptedException e) {
             // Catch block to handle the exception (e.g., if sleep is interrupted).
             e.printStackTrace();
         }
         // Close the current browser session
         driver.quit();
    }
}

Code Breakdown

The first and most important step is to add your credentials (username and access key) to the code.

Image 28

Then we create the URL for our LambdaTest Grid Server. This URL basically tells the program the path where LambdaTest Cloud Grid is hosted.

Image 29

Next, we must set the desired capabilities to run our test on the LambdaTest platform, defining requirements like browser name, browser version, platforms, and test name. You can generate your desired capability using the Desired Capability Generator.

Image 30

The RemoteWebDriver class implements the WebDriver interface and is used to run test scripts on a remote machine. Finally, we need to use this class to initiate our remote server using the below code:

Image 31

Congratulations! You have completed automation testing with the cloud-based testing grid. Now, you can find your test results under Automation> Web Automation.

Image 32

Conclusion

Selenium with Java, is great for automation testing. In this article, we kick-started our journey with automation testing by learning the basics of Selenium and creating our first test using Selenium Java. We explored how cloud-based testing platforms like LambdaTest can help us optimize and enhance our test coverage.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I'm M Mohammed Afsal(Afzal), a results-driven hustler with a strong focus on growth, product strategy, and marketing. My expertise lies in driving impactful initiatives, creating SEO-optimized content, and fostering engaging experiences to reach and engage with audiences effectively.

Currently, I am working on the Product Led Growth (PLG) initiative at LambdaTest. I am deeply involved in creating SEO-optimized content around automation testing, ensuring that LambdaTest is at the forefront of industry discussions and providing valuable insights to our target audience.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA3-Nov-23 6:05
professionalȘtefan-Mihai MOGA3-Nov-23 6:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.