Select random value in the Weblist

In the previous post, we have seen how to work with check boxes and radio button in selenium.In this post, we will see how to Select random value in the Weblist.

In any scenario, if there is a requirement that you need to test the functionality with different data. If you have a WebList in you application , then instead of passing data from any source you can instruct the code to select a random value in the WebList each time you run the code.

For generating the random value, We will use class ‘Random’ and instruct it to generate the number between 0 to 4. Because in our demo application, We have 5 values in our WebList.

Random random = new Random();
int index = random.nextInt(5); // It will give a range between 0 to 4

Code for selecting the random value in a weblist:

public class SelectRandValue {
	private static WebDriver driver;
	public static void main(String[] args) throws InterruptedException {
		
		driver = new FirefoxDriver();
		
		driver.manage().window().maximize();
		driver.get("https://testingpool.com/wp-content/uploads/2015/08/DemoApplication.html");
		driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
		Random random = new Random();
		int index = random.nextInt(5);  // It will give a range between 0 to 4
		System.out.println("Index is "+index);
		WebElement listBox = driver.findElement(By.xpath("//select[@name='number']")); //Weblist for number
		Select list = new Select(listBox);
		list.selectByIndex(index);
	}
}

Now, every time you run the code, it will select a different value into the weblist.


Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...