The following test is tricky:
@Test
public void searchReturnsResultsTest() {
//open page
driver.get(HOME_PAGE_URL);
//check that home page is displayed
Assert.assertEquals(driver.getCurrentUrl(), HOME_PAGE_URL);
//search for keyword
WebElement searchBox = driver.findElement(searchBoxName);
searchBox.sendKeys(KEYWORD);
WebElement searchButton = driver.findElement(searchButtonXpath);
searchButton.click();
//check that results page is displayed
Assert.assertEquals(driver.getCurrentUrl(), RESULTS_PAGE_URL);
//get all product names from the page
List<WebElement> productNames = driver.findElements(productNameXpath);
//check that all product names are not empty
for (WebElement productName : productNames)
Assert.assertFalse(productName.getText().isEmpty());
}
Why is this test tricky?
If the results page loads fast after searching, driver.findElements() returns a non-empty list of product names.
But if the results page loads slowly, driver.findElements() returns an empty list. The following for statement is skipped and the test passes without executing any assertions.
What should we do?
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.