Bird
Raised Fist0
Selenium Javatesting~15 mins

Select class for dropdowns in Selenium Java - Build an Automation Script

Choose your learning style10 modes available
Verify selecting an option from a dropdown using Select class
Preconditions (2)
Step 1: Locate the dropdown element by its id 'dropdownMenu'
Step 2: Create a Select object for the dropdown element
Step 3: Select the option with visible text 'Option 2'
Step 4: Verify that the selected option is 'Option 2'
✅ Expected Result: The dropdown selection changes to 'Option 2' and the selected option is confirmed
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Assert that the selected option's visible text is 'Option 2'
Best Practices:
Use the Select class to interact with dropdowns
Use explicit waits to ensure the dropdown is visible before interaction
Use meaningful locators like By.id
Use assertions from a testing framework like TestNG or JUnit
Automated Solution
Selenium Java
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.

Common Mistakes - 4 Pitfalls
Using driver.findElement().click() on dropdown options instead of Select class
Not waiting for the dropdown element to be visible before interacting
Using XPath with absolute paths for locating dropdown
{'mistake': 'Not verifying the selected option after selection', 'why_bad': 'Without verification, the test does not confirm if the selection actually happened.', 'correct_approach': "Use assertions to check the selected option's text matches the expected value."}
Bonus Challenge

Now add data-driven testing to select and verify three different options: 'Option 1', 'Option 2', and 'Option 3'.

Show Hint

Practice

(1/5)
1. What is the main purpose of the Select class in Selenium WebDriver?
easy
A. To perform mouse hover actions
B. To locate elements on the web page
C. To handle dropdown menus created with the <select> HTML tag
D. To take screenshots of the web page

Solution

  1. Step 1: Understand the Select class role

    The Select class is designed specifically to interact with dropdown menus that use the <select> HTML element.
  2. Step 2: Compare with other Selenium features

    Locating elements, mouse actions, and screenshots are handled by other classes and methods, not Select.
  3. Final Answer:

    To handle dropdown menus created with the <select> HTML tag -> Option C
  4. Quick Check:

    Select class = dropdown handler [OK]
Hint: Select class works only with <select> dropdowns [OK]
Common Mistakes:
  • Using Select for non-<select> dropdowns
  • Confusing Select with Actions class
  • Thinking Select locates elements
2. Which of the following is the correct way to create a Select object for a dropdown WebElement named dropdown?
easy
A. Select select = new SelectElement(dropdown);
B. Select select = new Select(dropdown);
C. Select select = Select(dropdown);
D. Select select = new select(dropdown);

Solution

  1. Step 1: Recall Select class constructor syntax

    The Select class constructor requires the WebElement as an argument and is called with 'new Select(element)'.
  2. Step 2: Check Java syntax correctness

    Java is case-sensitive; class names start with uppercase. The correct syntax is 'new Select(dropdown);'. Other options have syntax errors or wrong class names.
  3. Final Answer:

    Select select = new Select(dropdown); -> Option B
  4. Quick Check:

    Use 'new Select(element)' to create Select object [OK]
Hint: Use 'new Select(element)' with uppercase S [OK]
Common Mistakes:
  • Missing 'new' keyword
  • Wrong class name like SelectElement
  • Incorrect capitalization
3. Given the following code snippet, what will be the selected option's visible text after execution?
WebElement dropdown = driver.findElement(By.id("colors"));
Select select = new Select(dropdown);
select.selectByIndex(2);
String selected = select.getFirstSelectedOption().getText();

Assuming the dropdown options are:
0: Red
1: Green
2: Blue
3: Yellow
medium
A. "Blue"
B. "Red"
C. "Yellow"
D. "Green"

Solution

  1. Step 1: Understand selectByIndex behavior

    selectByIndex(2) selects the option at index 2, counting from 0.
  2. Step 2: Map index to option text

    Index 0 = Red, 1 = Green, 2 = Blue, so the selected option is "Blue".
  3. Final Answer:

    "Blue" -> Option A
  4. Quick Check:

    Index 2 = Blue [OK]
Hint: Index starts at 0, so 2 means third option [OK]
Common Mistakes:
  • Assuming index starts at 1
  • Confusing selectByIndex with selectByValue
  • Misreading option order
4. Identify the error in the following code snippet that tries to select an option by visible text:
WebElement dropdown = driver.findElement(By.name("fruits"));
Select select = new Select(dropdown);
select.selectByVisibleText("Apple");

Assume the dropdown is not a <select> element but a custom div-based dropdown.
medium
A. No error, code works fine
B. selectByVisibleText throws NullPointerException
C. selectByVisibleText throws NoSuchElementException
D. selectByVisibleText throws UnexpectedTagNameException

Solution

  1. Step 1: Check element type requirement for Select

    Select class works only with <select> HTML elements. Using it on a non-<select> element causes an error.
  2. Step 2: Identify exception thrown

    When Select is used on a non-<select> element, Selenium throws UnexpectedTagNameException.
  3. Final Answer:

    selectByVisibleText throws UnexpectedTagNameException -> Option D
  4. Quick Check:

    Select requires <select> tag, else UnexpectedTagNameException [OK]
Hint: Select only works on <select>, else UnexpectedTagNameException [OK]
Common Mistakes:
  • Assuming it throws NoSuchElementException
  • Ignoring element tag type
  • Expecting NullPointerException
5. You have a dropdown with options:
"Small", "Medium", "Large", "Extra Large"
Write the best way to select "Extra Large" using the Select class if you only know the option's value attribute is "xl" but the visible text is dynamic.
Which method should you use?
hard
A. select.selectByValue("xl");
B. select.selectByVisibleText("Extra Large");
C. select.selectByIndex(3);
D. select.selectByPartialVisibleText("Large");

Solution

  1. Step 1: Understand selection methods

    selectByVisibleText requires exact visible text, which is dynamic here, so not reliable.
  2. Step 2: Use value attribute for stable selection

    selectByValue("xl") uses the option's value attribute, which is stable and known.
  3. Step 3: Evaluate other options

    selectByIndex(3) depends on position which may change; selectByPartialVisibleText does not exist in Select class.
  4. Final Answer:

    select.selectByValue("xl"); -> Option A
  5. Quick Check:

    Use selectByValue for stable attribute selection [OK]
Hint: Use selectByValue when visible text is unreliable [OK]
Common Mistakes:
  • Using selectByVisibleText with dynamic text
  • Using invalid method selectByPartialVisibleText
  • Relying on index which may change
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard