Wednesday, 21 May 2014

Selenium WebDriver: Dropdown selection

Selenium has Select class designed to interact with drop down lists. Using it, we can easily choose option by displayed text, index or value.

Example:

Consider a dropdown list as shown below:

<select id="months" name="months">
<option value="">Select a month</option>
<option value="Jan">January</option>
<option value="Feb">February</option>
<option value="Mar">March</option>
</select>
view raw Select.html hosted with ❤ by GitHub

Now we just need to pass WebElement into Select Object as shown below

Select dropdown = new Select(driver.findElement(By.id("months")));

To select option say 'February', we can use any one of the method:
  • dropdown.selectByVisibleText("February");
  • dropdown.selectByValue("Feb");
  • dropdown.selectByIndex(2);

I have created a generic class Dropdown with all 3 methods shown above, we just need to call it.

  • Dropdown.selectByVisibleText(driver, By.id("months"), "February");
  • Dropdown.selectByValue(driver, By.id("months"), "Feb");
  • Dropdown.selectByIndex(driver, By.id("months"), 2);


package com.example.tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
public class Dropdown{
/**
* Select all options that display text matching the argument.
* @param driver
* @param by
* @param text
*/
public static void selectByVisibleText(WebDriver driver, By by, String text){
Select droplist = new Select(driver.findElement(by));
droplist.selectByVisibleText(text);
}
/**
* Select all options that have a value matching the argument.
* @param driver
* @param by
* @param value
*/
public static void selectByValue(WebDriver driver, By by, String value){
Select droplist = new Select(driver.findElement(by));
droplist.selectByValue(value);
}
/**
* Select the option at the given index.
* @param driver
* @param by
* @param index
*/
public static void selectByIndex(WebDriver driver, By by, int index){
Select droplist = new Select(driver.findElement(by));
droplist.selectByIndex(index);
}
}
view raw Dropdown.java hosted with ❤ by GitHub


No comments:

Post a Comment