My rule of thumb when designing UI tests is to do a basic check that the UI works, but coverage of the exact logic really should be shifted further down the testing pyramid (this will save execution time, plus lower level tests are better suited to it). A simple check of the first and last elements should suffice. That said, if you don't have good coverage on a lower level, some coverage is better than none.
First, let's say you can retrieve a list of elements in your page object:
By stuffSelector = By.id("stuff-");
public List<WebElement> getStuffList(){
return getDriver().findElements(stuffSelector);
}
// alternative java8 solution which makes it easier dealing with strings instead of webelements
public List<String> getStuffStringList() {
return getDriver().findElements(stuffSelector).stream()
.map(WebElement::getText)
.collect(Collectors.toList());
}
If you have pagination, you'll have to loop whilst there are more pages and add it to the list as you go:
public List<WebElement> getPaginatedStuffList() {
List<WebElement> stuff = getStuffList();
boolean morePages = areThereMorePages(); // implement this yourself
while(morePages) {
clickNextButton();
stuff.addAll(getStuffList());
morePages = areThereMorePages();
}
return stuff;
}
What you can then do is get an unsorted list before it's sorted, hit your UI sort, and grab a second sorted list.
Then sort your first list through code, and make sure that it's the same as your second list.
List<WebElement> list1 = somePage.getStuffList();
somePage.sortStuff();
List<WebElement> list2 = somePage.getStuffList();
// sorts list1 according to a comparator - I've simply compared the texts of the elements but you may wish to do something more complex..
list1.sort((e1, e2) -> e1.getText().compareTo(e2.getText()));
// feel free to iterate over the whole list if you really want
assertThat(list1.get(0).getText()).isEqualTo(list2.get(0).getText());
Honestly, this is pretty verbose, though. If you have access to the excellent AssertJ libraries, you can assert a list is sorted using a comparator directly.
List<WebElement> stuff = somePage.getStuffList();
assertThat(stuff).isSortedAccordingTo((e1, e2) -> e1.getText().compareTo(e2.getText()));