Handling Drop Down in WebDriver seems so tedious but WebDriver API has gifted us with one class Select and this is one good option to replace WebElement to handle Drop -Down and some time it also works for List also.
So let start with small part of HTML code
<select name="height"> <option value="3">3ft</option> <option value="4">4ft</option> <option value="5">5ft</option> <option value="6">6ft</option> </select>
3ft4ft5ft6ftBut always remember this works only on Select tag that is used for creating Drop down and list.
Select Class in WebDriver has many methods and function that interacts with Drop Down.
so let see how we should handle drop down
@Test
public void test()
{
driver.get("C:/Users/kaushal/Desktop/Size_DropDown.htm");
/*to get options of drop down we would use name=height attribute that is given in above code
*/
Select select = new Select(driver.findElement(By.name("height")));
//finding the number of option using size() function
int i =select.getOptions().size();
//printing the size
System.out.print("number of options ="+i);
//verifying number of option is 4
assertEquals(4, select.getOptions().size());
// selecting option in Drop-down using Visible Text
select.selectByVisibleText("5ft");
assertEquals("5ft", select.getFirstSelectedOption().getText());
//selecting option in Drop-down using value attribute
select.selectByValue("4");
assertEquals("4ft", select.getFirstSelectedOption().getText());
//selecting option in Drop-down using value attribute
select.selectByIndex(1);
assertEquals("4ft", select.getFirstSelectedOption().getText());
/*verifying the options of drop down first we would put all value in one list and then we would add all value fetched from instance of Select Class that we have used before in code in another array list and then we would verify the value*/
//first string type list that would contain all option value
List list = Arrays.asList(new String[]{"3ft",
"4ft", "5ft","6ft"});
List list1 = new ArrayList();
//adding all option captured by select in to list1 arraylist
for(WebElement element:select.getOptions())
{
list1.add(element.getText());
}
//to see what is being added to arraylist use this code
int j = list1.size();
System.out.println("value entered in J ="+j);
for(int k = 1; k<j; k++)
{
System.out.println(list1.get(k));
}
Assert.assertArrayEquals(list.toArray(), list1.toArray());
}
I have used this code and where working fine..to execute this code I have used Junit framework and would let you know once I would performa the same with Testng framework
Hi Dwarika,
Thanks for the post but while i was using above example , i am getting an error message as “The method assertEquals(int, int) is undefined for the type GoogleSuggest” where GoogleSuggest is the name of the class.
Can you please suggest something on this?