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.
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.
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.
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.
- 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.
- 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.
- 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)
- Similarly, you can create a new Java class by navigating to File > New > Class.
- 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.
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.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FirstProject {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://lambdatest.github.io/sample-todo-app/");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(driver.getTitle());
driver.quit();
}
}
Console Output
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.
Next, we initialize the WebDriver for the Chrome browser using the ChromeDriver()
method.
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.
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.
After all the test objectives are achieved, it's time to close the browser session and free the system’s memory.
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.
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) {
WebDriver driver = new FirefoxDriver();
driver.get("https://lambdatest.github.io/sample-todo-app/");
WebElement inputbar = driver.findElement(By.id("sampletodotext"));
inputbar.sendKeys("New todo task added");
WebElement submitBtn = driver.findElement(By.id("addbutton"));
submitBtn.click();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.quit();
}
}
Output
Code Walkthrough
In this example, we must import the WebElement
and By
class to select elements on the web page for interaction.
Then we initialize the Firefox browser using the below code.
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.
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.
Next, we should select the submit button using the WebElement
class.
Finally, we can click on the add button using click()
method provided by the WebElement
class to add our Todo item to the list.
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:
- First, navigate to Eclipse Marketplace and install the TestNG plugin. Once installed, you can find it under the Installed section.
- 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.
Now that we have integrated TestNG into the project let’s create the first parallel test execution script.
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();
driver.get("https://lambdatest.github.io/sample-todo-app/");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(driver.getTitle());
}
@Test
void addNewTodoItem () {
WebDriver driver = new FirefoxDriver();
driver.get("https://lambdatest.github.io/sample-todo-app/");
WebElement inputbar = driver.findElement(By.id("sampletodotext"));
inputbar.sendKeys("New todo task added");
WebElement submitBtn = driver.findElement(By.id("addbutton"));
submitBtn.click();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@AfterMethod
public void tearDown() throws Exception {
if (driver != null) {
driver.quit();
}
}
}
TestNG configuration XML file
="1.0"="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>
</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.
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:
- Create a LambdaTest account and complete all the required processes.
- To get your credentials, go to your profile icon in the top right corner and navigate to Account Settings.
- Then go to Password & Security. You can find your Username and Access Key and save it for future use.
To run our code on the LambdaTest, you need to modify our test case. So here is the modified code.
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 {
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() {
URL finalGridURL = new URL("https://" + username + ":" + accesskey + gridURL)
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("browserName", "Firefox");
capabilities.setCapability("platformName", "macOS Ventura");
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();
driver.get("https://lambdatest.github.io/sample-todo-app/");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(driver.getTitle());
driver.quit();
}
void addNewTodoItem () {
setUp();
WebDriver driver = new FirefoxDriver();
driver.get("https://lambdatest.github.io/sample-todo-app/");
WebElement inputbar = driver.findElement(By.id("sampletodotext"));
inputbar.sendKeys("New todo task added");
WebElement submitBtn = driver.findElement(By.id("addbutton"));
submitBtn.click();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.quit();
}
}
Code Breakdown
The first and most important step is to add your credentials (username and access key) to the code.
Then we create the URL for our LambdaTest Grid Server. This URL basically tells the program the path where LambdaTest Cloud Grid is hosted.
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.
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:
Congratulations! You have completed automation testing with the cloud-based testing grid. Now, you can find your test results under Automation> Web Automation.
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.