In this example, we will modify the search test we created in earlier chapters to test the results containing the list of expected products, as shown in the following code:
@Test
public void searchProduct() {
// find search box and enter search string
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("Phones");
WebElement searchButton =
driver.findElement(By.className("search-button"));
searchButton.click();
assertThat(driver.getTitle())
.isEqualTo("Search results for: 'Phones'");
List<WebElement> searchItems = driver
.findElements(By.cssSelector("h2.product-name a"));
List<String> expectedProductNames =
Arrays.asList("MADISON EARBUDS",
"MADISON OVEREAR HEADPHONES",
"MP3 PLAYER WITH AUDIO");
List<String> productNames = searchItems.stream()
.map(WebElement::getText)
.collect(Collectors.toList());
assertThat(productNames).
isEqualTo(expectedProductNames);
}
In the preceding code, we created a list of all the matching products returned by the findElements() method. We then retrieved the text of each element by calling the map() function and mapped the return values to a list of strings. This is compared with the expectedProductNames list.