Reusable TableHelper Class in Selenium Automation Test
In our daily GUI automation testing, very often we need to check element value from a table. Normally we need to find the table, then locate the specific row or column, then the cell element value. If each time we repeat these steps, it definitely sounds not wise enough. Remember to be DRY—Don’t Repeat Yourself. Thus we can create a helper class to make these functions reusable – to build a robust Automation Test Framework, it is necessary to design lots of Helper classes and Utility classes.
Here I don’t implement all required functions, just one – to get text value of a specific cell from a table. You can decide what other methods to add per the character of your project.
public Optional<String> getCellData(int rowIdx, int colIdx) {
List<WebElement> tableRows = table.findElements(By.tagName(“tr”));
if (tableRows.size() <= rowIdx) {
logger.error(String.format(“Unable to find row %d, out of index”, rowIdx));
return Optional.empty();
}
WebElement currentRow = tableRows.get(rowIdx – 1);
List<WebElement> tableCols = currentRow.findElements(By.tagName(“td”));
if (tableCols.size() <= colIdx) {
logger.error(String.format(“Unable to find column %d, out of index”, colIdx));
return Optional.empty();
}
WebElement cell = tableCols.get(colIdx – 1);
return Optional.ofNullable(cell.getText());
}
As you can see, I use Optional as return type. In case there is no specific cell found, this method will not return null. As one principle of our framework design, we should try to avoid returning null from our helper class or utility class methods.
Happy automation test~~~~