132. Using selectByIndex( ) command with Drop Down field






selectByIndex( ) command can be used to select the list option from the Drop Down field using the specified Index of the List Option.

Index value starts from 0.

  • If  you specify the Index value as 0, the First List option in the Drop Down field will get selected
  • If  you specify the Index value as 1, the Second List option in the Drop Down field will get selected
  • And so on....

In order to use the selectByIndex( ) command, we have to create an object for Select class of selenium as shown below:

 Select select = new Select(_driver.findElement(By.cssPath("CSS Path of Drop Down field")));

  • Here Select is the Class name
  • select is the object of Select Class

After creating an object for Select Class, you can get the selectByIndex( ) predefined method of Select Class by using its object select as shown below:

select.selectByIndex(0);  -> This will select the first list option from the Drop Down field



Test Description:

Understand the test description by reading the comments mentioned on the below screenshot:




Lets Implement This:

Pre-requisites:

1. Create a new Java Project say 'WebDriver-Project51' in Eclipse IDE
2. Configure the Project to work with Selenium WebDriver
3. Create a package say 'package51' under the newly created project.
4. Create a Java Class file say 'Class51' under the newly created package as shown below:




Actual Steps:

1. Write the following code into the newly created Java Class file as shown below and make sure that you resolve all the errors before going to next step:





2. Write the test method 'selectByIndexDemo( )' which uses CSS Path Statement for locating the  Drop Down field as shown below:




3. Save and Run the 'Class51.java' file by selecting the 'JUnit Test' option and ensure that our Automation Test has selected the list option with index 0 (i.e. First list option) from the Drop Down field as shown in the below video:

Watch the below video:

Click here to watch the video.

Download this Project:


Click here to download this project and import into Eclipse IDE  on your machine.


Please comment below to feedback or ask questions.

Using selectByValue( ) command with Drop Down field will be explained in the next post.


 

Followers

Labels