Sometimes, you need to assert that each value from a list is correct:
@Test
public void allProductNamesContainKeywordTest() {
driver.get(HOME_PAGE_URL);
Assert.assertEquals(driver.getCurrentUrl(), HOME_PAGE_URL);
WebElement searchBox = driver.findElement(searchBoxBy);
searchBox.sendKeys(KEYWORD);
WebElement searchButton = driver.findElement(searchButtonBy);
searchButton.click();
wait.until(ExpectedConditions.urlContains(RESULTS_PAGE_URL));
List<WebElement> productNames = driver.findElements(productNameBy);
Assert.assertEquals(24, productNames.size());
for (WebElement p : productNames) {
String productName = p.getText();
Assert.assertTrue(productName.toLowerCase().contains(KEYWORD));
}
}
The test case implemented by this test method is very simple:
opens the site
searches for a keyword
waits until the results page is displayed
gets all product names displayed in the page
asserts that there are 24 values in the product names list
asserts that each product name contains the search keyword
The test case is simple but the test method can be simpler.
It would be simpler if it would not use the FOR statement.
How can we get rid of it?
Keep reading with a 7-day free trial
Subscribe to Selenium For Beginners to keep reading this post and get 7 days of free access to the full post archives.