Monday, 26 March 2018

How to Handle Dropdown in Selenium webdriver

Hey guys in this post we are going to learn about how to handle simple dropdowns in Selenium Webdriver.For handling dropdowns Selenium already provides Select class that has some predefined method which help is a lot while working with Dropdown.

In the example given below we are using select by index , select by value and select by visible dropdown text. These are three different ways by which you can select dropdown values. plus we can so some more verification on dropdowns by verifiyting selected dropdown fields and we can also fetch all the dropdown data using selenium webdriver.

Try out below code and learn how we can automate dropdown testing for anyweb application using selenium webdriver.

Video Tutorial -



import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
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.Select;

public class DropDownTest {

 WebDriver driver;
 WebElement month_dropdown;
 
 @Before
 public void setup()
 {
  System.setProperty("webdriver.chrome.driver", "C:\\Softwares\\chromedriver_win32\\chromedriver.exe");
  
      driver=new ChromeDriver();

       driver.manage().window().maximize();

       driver.get("http://www.facebook.com");
       
     month_dropdown=driver.findElement(By.id("month"));
 }
 
 @Test
 public void testSelectByIndex()
 {
  
  Select month=new Select(month_dropdown);
   
   month.selectByIndex(4);
  
 }
 @Test
 public void testSelectByValues()
 {
  
   
   Select month=new Select(month_dropdown);
   
   month.selectByValue("5");
 }
 @Test
 public void testSelectByVisisbleField()
 {
  
   
   Select month=new Select(month_dropdown);
   
   month.selectByVisibleText("Aug");
 }
 @Test
 public void testSelectedOption()
 {
  
   
   Select month=new Select(month_dropdown);
   
   WebElement first_value=month.getFirstSelectedOption();
   
   String value=first_value.getText();
   
   System.out.println("select dropdown value is- "+value);
 }
 @Test
 public void testAllDropDownOptions()
 {
   
  Select month=new Select(month_dropdown);
   
  List<WebElement> dropdown=month.getOptions();
   
   for(int i=0;i<dropdown.size();i++){
   
   String drop_down_values=dropdown.get(i).getText();
   
   System.out.println("dropdown values are "+drop_down_values);
   
   }
   
   
 }
 
 @After
 public void teardown()
 {
  driver.quit();
 }
 
}

3 comments: