How to Select random value from a DropDownList using Selenium

Requirement:- We need to select random value from a given dropdownlist, to test the functionality how our AUT would behave under varying selection of options.


DropDownlist for random selection Selenium
DropDownlist + HTML code

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


Solution:-

(Selenium)
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.
//Creating the List object
List <WebElement> weblist = driver.findElements(By.xpath(".//*[@id='drpdwnTopics']/option"));
//Taking the count of items
int iCnt = weblist.size();

b.We can use the Select Class and implement its getOptions method to get the count.

Select objSel = new Select(driver.findElement(By.xpath(".//*[@id='drpdwnTopics']")));
List <WebElement> weblist = objSel.getOptions();
//Taking the count of items
int iCnt = weblist.size();

2.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.

Code




import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.*;


public class RandomSelectionDrpDwnList {
 WebDriver driver;
 @BeforeTest
 public void launch()
 {
  driver = new FirefoxDriver();
  driver.get(" ");
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(20000, TimeUnit.MILLISECONDS); 
 }
 
 @Test
 public void selectRandom()
 {
 //Object of the Dropdownlist
 WebElement drpDwnList = driver.findElement(By.xpath(".//*[@id='drpdwnTopics']"));
 //Using FindElements to create a List object
 //List <WebElement> weblist = driver.findElements(By.xpath(".//*[@id='drpdwnTopics']/option"));
 //Using Select Class to fetch the count
 Select objSel = new Select(drpDwnList);
 List <WebElement> weblist = objSel.getOptions();
 //Taking the count of items
 int iCnt = weblist.size();
 //Using Random class to generate random values
 Random num = new Random();
 int iSelect = num.nextInt(iCnt);
 //Selecting value from DropDownList
 objSel.selectByIndex(iSelect);
 //Selected Value
 System.out.println(drpDwnList.getAttribute("value"));
 }
 
 @AfterTest
 public void close()
 {
  //Closing the browser
  driver.quit();
 }
 
}