findElements for multiple matches in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.time.Duration; import java.util.List; public class SearchResultsTest { WebDriver driver; WebDriverWait wait; @BeforeClass public void setUp() { // Set path to chromedriver executable if needed driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.manage().window().maximize(); } @Test public void testMultipleProductItemsDisplayed() { driver.get("https://example-ecommerce.com"); // Enter 'laptop' in search box WebElement searchBox = wait.until(ExpectedConditions.elementToBeClickable(By.id("search-box"))); searchBox.sendKeys("laptop"); // Click search button WebElement searchButton = driver.findElement(By.id("search-button")); searchButton.click(); // Wait for product items to be visible wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("product-item"))); // Find all product items List<WebElement> productItems = driver.findElements(By.className("product-item")); // Assert at least 3 product items are displayed Assert.assertTrue(productItems.size() >= 3, "Expected at least 3 product items, but found " + productItems.size()); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
This test script uses Selenium WebDriver with Java and TestNG for assertions.
Setup: The @BeforeClass method initializes the ChromeDriver and WebDriverWait for explicit waits.
Test steps: The test navigates to the homepage, enters 'laptop' in the search box identified by id='search-box', clicks the search button id='search-button', then waits explicitly until at least one product item with class product-item is visible.
It then collects all elements with class product-item using findElements, which returns a list of matching elements.
Assertion: The test asserts that the list size is 3 or more, ensuring multiple products are displayed.
Teardown: The @AfterClass method closes the browser.
This approach uses explicit waits to avoid flaky tests and uses proper locators and assertions for reliability.
Now add data-driven testing with 3 different search keywords: 'laptop', 'smartphone', 'headphones'