Home > Enterprise >  How to check if a webpage is displaying results in A-Z or Z-A in selenium java
How to check if a webpage is displaying results in A-Z or Z-A in selenium java

Time:01-06

Trying to test a webpage which has a sorting option of A-Z and Z-A.

Is this something which can be verified with selenium i.e. when the user select Z-A then the page should display all products in the reverse order.

If I have a page containing 10 items with a range of names:

Apples Bananas Carrots Doughnuts Eggs Unicorn Zebra

If I select the A-Z sorting option then the above is fine, however if I were to select the Z-A option the page would appear like this:

Zebra Unicorn Eggs Doughnuts Carrots Bananas Apples

Is this possible to test in selenium? Any examples would be super useful. TIA

CodePudding user response:

First, you will need to locate the elements on the webpage that contain the results. You can do this using a method such as findElements or findElement, depending on whether there are multiple results or just one.

Once you have located the elements, you can use the getText method to retrieve the text of each element.

You can then store the text of each element in an array or list.

Once you have all of the results stored in an array or list, you can use the sort method to sort the array or list in either A-Z or Z-A order, depending on your preference.

Finally, you can use the assertEquals method to compare the sorted array or list with the original list of results to verify that they are in the correct order.

Sample code :

// Locate the elements containing the results
List<WebElement> results = driver.findElements(By.cssSelector("css selector for the results"));

// Retrieve the text of each element and store it in a list
List<String> resultTexts = new ArrayList<>();
for (WebElement result : results) {
    resultTexts.add(result.getText());
}

// Sort the list of results in A-Z order
Collections.sort(resultTexts);

// Verify that the results are in the correct order
assertEquals(resultTexts, results);
  • Related