Interacting with Radio Buttons and Radio Buttons Groups During an Automation Script

The aim is to create an automation script that interacts with radio buttons and radio buttons groups. For the following example, we will assume that the radio button element has been found by means of the findElement method (we will go into more detail about this method in an upcoming section):

WebElement masters = driver.findElement(By.
cssSelector("input[value='masters']"));

Open the https://trainingbypackt.github.io/Beginning-Selenium/lesson_3/exercise_3_1.html file and use IntelliJ IDEA for the creation of a Selenium script. The steps for completion of this process are as follows:

  1. Review and analyze the structure and behavior of the https://trainingbypackt.github.io/Beginning-Selenium/lesson_3/exercise_3_1.html file.
  2. Create a new Java file for the automation script. Make sure that you include the required libraries.
package com.beginningselenium.selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
  1. Locate the radio button "Masters":
WebElement masters = driver.findElement(By.
cssSelector("input[value='masters']"));

If we know that the radio button we want to work with belongs to a group, we can locate the group by its name:

List<WebElement> degreeLevel = driver.findElements(By.
name("degree"));
And iterate through its elements:
for (WebElement degree : degreeLevel)
{
if(degree.getAttribute("value").equals("masters"))
{
if(!degree.isSelected()) {
type.click();
}
break;
}
}
  1. Verify that the radio button "Masters" is enabled and visible:
if (masters.isEnabled() && masters.isDisplayed())
{

}

  1. Using the System.out.println method, display messages indicating whether the verification was successful or not:
System.out.println("The radio button is enabled and
visible.");
  1. If the radio button is enabled and visible, verify that it is not selected before clicking on it:
if (masters.isEnabled() && masters.isDisplayed())
{
if (!masters.isSelected())
{
masters.click();
}
}

We can select a radio button by clicking on it after it has been selected.

  1. Verify that "Masters" has been selected and use the System.out.println method to display messages, indicating whether the verification was successful or not and the option chosen:
if (masters.isEnabled() && masters.isDisplayed())
{
if (!masters.isSelected())
{
masters.click();
if (masters.isSelected())
System.out.println("It worked, the 'Masters'
option was selected");
else
System.out.println("Something went wrong,
'Masters' was not selected.");
}
}
  1. Compile and run the script.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.102.182