In this post, I will illustrate how to select random value into Dropdown field while designing effective automation script using selenium Webdriver.
Please find below sample code for the same.
Sample Code:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
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.BeforeClass;
import org.testng.annotations.Test;
public class RandomdropDownValues {
public WebDriver driver;
ArrayList<String> al ;
@BeforeClass
public void setup(){
driver = new FirefoxDriver();
driver.get("https://www.orangehrm.com/OrangeHRM_Contact_Hotlines");
driver.manage().window().maximize();
}
@Test
public void randomdropDownValues(){
driver.findElement(By.xpath("//a[@href='#myModal_1']")).click();
WebElement wb = driver.findElement(By.xpath("//iframe[@src='contatcForm.php']"));
driver.switchTo().frame(wb);
//To get the all dropdown values from country field
List<WebElement> se = new Select(driver.findElement(By.xpath("//select[@id='country']"))).getOptions();
al = new ArrayList<String>();
for(int i=0;i<se.size();i++){
//getting all the data from dropdown
String dvalues =se.get(i).getText();
//Storing each value in array list
al.add(dvalues);
}
//generating random integer value
Random foo = new Random();
int randomNumber = foo.nextInt(al.size()- 0) + 0;
//getting random data from array List
String randomCountry=al.get(randomNumber);
//passing random data into dropdown field
driver.findElement(By.xpath("//select[@id='country']")).sendKeys(randomCountry);
}