How to Select Random Radio Button Selenium WebDriver with Java

While automating a form selection with Selenium and Java, It’s a good practice to randomize your form values. Here is how you can select random values on radio buttons. Lets suppose you have a radio button form field with name ‘radio_example’. Which has three radio buttons with values ‘Yes’, ‘No’ and “MayBe’.

<input name="radio_example" type="radio" value="Yes">
<input name="radio_example" type="radio" value="No">
<input name="radio_example" type="radio" value="MayBe">

Java code with Selenium Webdriver to select random radio button

driver.findElement(By.xpath("(//input[@name='radio_example'])["+getRandomInteger(1,3)+"]")).click();

private int getRandomInteger(int min, int max){
    return ThreadLocalRandom.current().nextInt(min, max+1);
}

here getRandomInteger() returns random integer within min and max range.

Site Footer