Automation QA Testing Course Content

How to select random option from dropdown in Webpage Using Selenium Webdriver

How to Select random value from a DropDownList using Selenium
We need to select random value from a given dropdownlist, to test the functionality how our AUT
would behave under varying selection of options
Approach:-
1.We would take the count of existing options in the weblist/dropdownlist .
2.Take a random value between 0(starting index of the dropdownlist, we can avoid in our case as we have --Select-- at 0 index) and maximum value -1(total available options in the list)
3.Select the value based on the random value

1.How to take count of items:-
a.We can use Findelements method to return a list of items and further we would use getSize method of list to fetch the count value.

Steps to Follow:

a)identify the dropdown
WebElement drp=driver.findElement(By.locator("locatorvalue"));

b.We can use the Select Class and implement its getOptions method to get the count.
Select objSel = new Select(drp);
c.fetch all the dropdown options from dropdown
List <WebElement> weblist = objSel.getOptions();
d.//Taking the count of elements in collection
int iCnt = weblist.size();


How to generate random number, we would implement "Random" class and use its nextInt method to
output the random number between the given range.
Note:- nextInt, method would generate number from 0 to upperlimit-1, example nextInt(10), would generate numbers between 0 and 9.
for(int i=1;i<5;i++){
 //Using Random class to generate random values
 Random r = new Random();
 int rnum = r.nextInt(iCnt);
 //Selecting value from DropDownList
 objSel.selectByIndex(rnum);
 //Selected Value
 System.out.println(objSel.getFirstSelectedOption().getText());
 }

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.