Google+

419. Using getFirstSelectedOption( ) with drop down field to retrieve the label text of the list option that is currently selected







getFirstSelectedOption Selenium WebDriver command is used to retrieve the label of the list option that is currently selected in the drop down field. 

In order to use the getFirstSelectedOption( ) command with drop down field, we have to create an object for Select class of selenium for Drop down field 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 getFirstSelectedOption( ) predefined method of Select Class by using its object select as shown below:

select.getFirstSelectedOption( );  

But the above statement will return the web element (i.e. retrieved list option from the dropdown field).
As our requirement is to retrieve the label text of the element that is currently selected, we have to use getText( ) command to retrieve the label text of the retrieved Web Element by modifying the above statement as shown below:

select.getFirstSelectedOption( ).getText( );   -> This will retrieve the label text of the current selected list option.


Test Description:

Now lets use getFirstSelectedOption( ) method to retrieve the label text of the selected list option as explained in the below screenshot:



Lets Implement the Test on Eclipse IDE:

Pre-requisites:

1. Create a new Java Project say 'WebDriver-Project63' in Eclipse IDE
2. Configure the Project to work with Selenium WebDriver
3. Create a package say 'package63' under the newly created project.
4. Create a Java Class file say 'Class63' 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. Create a test method 'getFirstSelectedOptionDemo()' which uses CSS Path Statement for locating the  Drop Down field as shown below:



3. Save and Run the 'Class63.java' file by selecting the 'JUnit Test' option and ensure that our Automation Test has retrieved the label text of the list option that is currently selected in the drop down field and also entered the retrieved label text into a Username text box 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 getFirstSelectedOption( ) with Multi-Selection Box field to retrieve the label text of the option that is selected first in the field  will be explained in the next post.


No comments:

Blog Index