Selenium WebDriver to select combo-box item?

Paul McKenzie picture Paul McKenzie · Aug 3, 2011 · Viewed 68.8k times · Source

We are using Selenium WebDriver and JBehave to run "integration" tests on our web-app. I have a method that will enter a value into a form input.

@When("I enter $elementId value $value")
public void enterElementText(final String elementId, final String value) {
    final WebElement webElement = webdriver.findElement(By.id(elementId));
    webElement.clear();
    webElement.sendKeys(value);
}

But when I try to use this to select an item in a drop-down list it (unsurprisingly) fails

java.lang.UnsupportedOperationException: You may only set the value of elements that are input elements

How do I select a value in the combo?

Answer

Paul McKenzie picture Paul McKenzie · Aug 4, 2011

This is how to do it:

@When("I select $elementId value $value")
public void selectComboValue(final String elementId, final String value) {
    final Select selectBox = new Select(web.findElement(By.id(elementId)));
    selectBox.selectByValue(value);
}