Select class for dropdowns 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.Select; 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; public class DropdownSelectTest { WebDriver driver; WebDriverWait wait; @BeforeClass public void setUp() { // Set path to chromedriver if needed driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.get("https://example.com/dropdownpage"); } @Test public void testSelectOptionByVisibleText() { // Wait until dropdown is visible WebElement dropdownElement = wait.until( ExpectedConditions.visibilityOfElementLocated(By.id("dropdownMenu")) ); // Create Select object Select dropdown = new Select(dropdownElement); // Select option with visible text 'Option 2' dropdown.selectByVisibleText("Option 2"); // Verify selected option is 'Option 2' String selectedOption = dropdown.getFirstSelectedOption().getText(); Assert.assertEquals(selectedOption, "Option 2", "Selected option should be 'Option 2'"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
This test script uses Selenium WebDriver with Java and TestNG framework.
In setUp(), we open the browser and navigate to the page with the dropdown.
In the test method, we wait explicitly for the dropdown to be visible using WebDriverWait and ExpectedConditions. This avoids timing issues.
We locate the dropdown by its id and create a Select object to interact with it.
We select the option by its visible text 'Option 2' using selectByVisibleText.
Then we get the currently selected option's text and assert it equals 'Option 2' to confirm the selection worked.
Finally, in tearDown(), we close the browser to clean up.
This structure follows best practices: explicit waits, meaningful locators, using the Select class, and proper assertions.
Now add data-driven testing to select and verify three different options: 'Option 1', 'Option 2', and 'Option 3'.