Many websites have results pages.
Each result may have a name, an author, a price.
The results pages have usually also a way of changing the sort order so that results can be sorted by
name
author
price
After the results page is reloaded with the new sort order enabled, you may want to check that the results are in the proper order.
How do you do this?
See below a possible solution for checking that products are sorted by name ascending:
List<WebElement> nameList = driver.findElements(PRODUCT_NAME);
List<String> names = nameList.stream()
.map(n -> n.getText())
.collect(Collectors.toList());
List<String> sortedNames = names;
Collections.sort(sortedNames);
boolean areSorted = names.equals(sortedNames);
Just 5 lines of code! Pretty good, don’t you think?
Line 1 finds all product name elements and saves them to the nameList variable.
Line 2 creates a stream from the nameList list, gets the value for each name element and creates a list with all name values. The result is saved in a list of strings (names).
Line 3 creates a new list of strings variable (sortNames) and saves into it the names variable.
Line 4 sorts the sortNames list ascending.
Line 5 compares sortNames and names.
If they are equal, the product names are sorted, otherwise, the product names are not sorted.