A common use case for automated tests is validating data in an HTML table.
In this blog post, I will share one technique to do this using Cucumber DataTables and Selenium WebDriver.
Let’s say we are looking to validate the entries in the following example table from w3schools.com:
If we inspect the HTML table, here is the code behind it:
The example table is made up of 7 rows (the first row being the header row) where each row has three columns. How do we validate this? Thankfully, Cucumber includes a handy data type to do this cleanly called a "DataTable" that we can pass via Cucumber step definitions.
For simplicity's sake, let's assume we are not going to be validating the "header" row of the table, just the rows containing the data. We'll start by writing the Cucumber step definition. Here is one way that could look:
We will be passing a Cucumber DataTable to our validation code in the "Then" step. Below is the Java code for the "Then" step:
We can define the data text below the "Then" step as a Cucumber DataTable by declaring the input parameter of that step definition as a DataTable type (I'm importing the package io.cucumber.datatable.DataTable to do that). The Cucumber DataTable object will allow us to work with the "expected" data in a row by row, column by column basis which works great for validating data within an HTML table.
Next, let's take a look at the Java code used to verify the HTML table. Below is the code for the Class HtmlTableValidationPage.java:
The code is commented to describe its functionality. In short, all I'm doing is looping through every row and every cell (column) in the DataTable, grabbing the matching row and cell from the HTML table, and validating that the text contents are the same. Below is the resulting console output:
Jared Hoernemann is a Senior Automation Engineer specializing in designing and coding test automation scripts and frameworks from the ground up, as well as mentoring other developers. Jared designs, implements, and executes automated tests for web browsers, APIs of all kinds, and databases.
Have a QA question?
Our team would love to help!