Many of you might have come across with this requirement like validating sorting or searching functionality in a application. Today I am going to discuss how to achieve this using selenium web driver.

Sorting functionality - Suppose you need to verify that records in a table are sorted or not after clicking on the sort button or column header. You can follow the below logic to do this validation.
     a) Make sure you have enough test data to test sorting functionality
     b) Read all the values of a column in the table to be sorted in a data structure like list from the first page of the table
     c) Click on the next page link and once next page is loaded do the same operation as in step b)
     d) Continue until you reach the last page
     e) Sort the list using any build in function/method provided by the language you are using. By the end of this step you will be having the list of expected list of records in a sorted order.
     e) Now come back to the first page and click on the sort button or column header to sort the list from the application.
     f) Follow the steps b) to d) and create the list of actual result.
     g) Now compare expected list with actual list, your test should pass only when both the list are same.

You can use the following method in java for reading table data into a list:

LinkedList<String> getTableColumnData(int column_no, String tableName)
{
        LinkedList<String> values = new LinkedList<String>();
        WebElement table = getWebDriver().findElement(By.className(tableName));
List<WebElement> rows = table.findElements(By.tagName("tr"));
Iterator<WebElement> i = rows.iterator();
while(i.hasNext())
{
   WebElement row=i.next();
   List<WebElement> columns= row.findElements(By.tagName("td"));
    Iterator<WebElement> j = columns.iterator();
    int count =0;
    String value;
   while(j.hasNext())
   {
         WebElement column = j.next();
         if(count == column_no)
 {
         String data = column.getText();
   value = data;
  values.add(value);
  break;
  }
         count ++;
              }

}

return values;
}
 
You have to call this function in each page of your application until you reach the last page.
   
Following method can be used for checking if both the lists are same:

boolean isTableColumnSorted(LinkedList<String> expected, LinkedList<String> actual)
{
boolean result = false;
Collections.sort(expected);
if(CollectionUtils.isEqualCollection(expected,actual))
result = true;
return result;
}

I will explain the logic and code for testing filter functionality in my next post. Please do share your comments on this.