Automating Table Sorting with Selenium and TestNG: A Step-by-Step Guide


In today’s world of web development and testing, automating repetitive tasks is essential for efficiency and accuracy. One such task is verifying the sorting functionality of HTML tables. In this blog post, we’ll walk through how to automate the process of sorting a table and verifying its correctness using Selenium WebDriver, TestNG, and Java.
The Problem
Imagine you have a webpage with a table that can be sorted by clicking a button. Your goal is to:
Automate the process of clicking the sort button.
Extract the data from the table.
Verify that the table is sorted correctly.
To achieve this, we’ll use the following tools and libraries:
Selenium WebDriver: For browser automation.
TestNG: For test management and assertions.
WebDriverManager: For managing browser drivers.
Java Collections: For sorting and comparing lists.
The Code
Below is the complete Java code for automating the table sorting verification:
package me.hossain.ebrahim;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortingTable {
WebDriver driver;
@BeforeSuite
public void startChromeBrowser() {
// Set up ChromeDriver using WebDriverManager
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
// Navigate to the target webpage
driver.get("https://www.w3schools.com/howto/howto_js_sort_table.asp");
}
@Test
public void sorting() {
// Click on the Sort button
driver.findElement(By.xpath("//button[contains(text(),'Sort')]")).click();
// Fetch the list of elements from the first column of the table
List<WebElement> tdList = driver.findElements(By.xpath("//table[@id='myTable']/tbody/tr/td[1]"));
// Extract text from the table cells and store in a list
List<String> originalList = new ArrayList<>();
for (WebElement td : tdList) {
originalList.add(td.getText());
}
// Print the original list
System.out.println("Original List:");
for (String item : originalList) {
System.out.println(item);
}
// Create a copy of the original list and sort it
List<String> sortedList = new ArrayList<>(originalList);
Collections.sort(sortedList);
// Print the sorted list
System.out.println("\nSorted List:");
for (String item : sortedList) {
System.out.println(item);
}
// Verify if the original list is sorted
if (originalList.equals(sortedList)) {
System.out.println("\nThe list is correctly sorted.");
} else {
System.out.println("\nThe list is not correctly sorted.");
}
}
@AfterSuite
public void closeChromeBrowser() {
// Close the browser
driver.close();
}
}
Step-by-Step Breakdown
1. Setting Up the Environment
We use WebDriverManager to automatically manage the ChromeDriver executable. This eliminates the need to manually download and configure the driver.
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.w3schools.com/howto/howto_js_sort_table.asp");
2. Clicking the Sort Button
The sorting()
method begins by locating and clicking the "Sort" button on the webpage using an XPath selector.
driver.findElement(By.xpath("//button[contains(text(),'Sort')]")).click();
3. Extracting Table Data
After sorting, we extract the data from the first column of the table. We use an XPath selector to locate all <td>
elements in the first column and store their text in a list.
List<WebElement> tdList = driver.findElements(By.xpath("//table[@id='myTable']/tbody/tr/td[1]"));
List<String> originalList = new ArrayList<>();
for (WebElement td : tdList) {
originalList.add(td.getText());
}
4. Sorting and Comparing
We create a copy of the original list and sort it using Collections.sort()
. Then, we compare the sorted list with the original list to verify if the table is sorted correctly.
List<String> sortedList = new ArrayList<>(originalList);
Collections.sort(sortedList);
if (originalList.equals(sortedList)) {
System.out.println("\nThe list is correctly sorted.");
} else {
System.out.println("\nThe list is not correctly sorted.");
}
5. Cleaning Up
Finally, we close the browser after the test is complete.
driver.close();
Running the Test
To run this test, ensure you have the following dependencies in your pom.xml
(if using Maven):
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.10.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.8.0</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>5.4.1</version>
</dependency>
</dependencies>
Run the test using TestNG, and you’ll see the original and sorted lists printed in the console, along with a message indicating whether the table is correctly sorted.
Conclusion
Automating table sorting verification is a great way to ensure the functionality of your web application. By leveraging Selenium, TestNG, and Java, we can easily automate this process and integrate it into our testing pipeline. This approach can be extended to more complex scenarios, such as sorting by multiple columns or handling dynamic data.
Feel free to modify the code and experiment with different webpages and tables. Happy testing! 🚀
Subscribe to my newsletter
Read articles from Md. Ebrahim Hossain directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Md. Ebrahim Hossain
Md. Ebrahim Hossain
With years of hands-on experience, I've become proficient in a wide range of testing domains, including Manual Testing, API Testing, Automation Testing, Database Testing, and Performance Testing. My passion for ensuring software excellence extends beyond testing; I also excel as an SQA Mentor, guiding aspiring professionals on their journey to mastering the craft.