被测试的HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form>
<input type = "radio" name = "fruit" value = "berry"/>草莓</input>
<br/>
<input type = "radio" name = "fruit" value = "watermelon"/>西瓜</input>
<br/>
<input type = "radio" name = "fruit" value = "orange"/>橙子</input>
</form>
</body>
</html>
- 先定位到单选按钮,再用isSelected()方法判断有没有被选中
WebElement radioOption = driver.findElement(By.xpath("//input[@value='berry']"));
radioOption.isSelected();//使用isSelected()方法判断单选按钮有没有被选中
完整代码
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class OperateRadio {
WebDriver driver;
String baseUrl = "E:\\HTML\\radioButton.html";
@BeforeMethod
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void testRadio() throws Exception {
driver.get(baseUrl);
Thread.sleep(1000);
//查找属性为"berry"的单选按钮对象
WebElement radioOption = driver.findElement(By.xpath("//input[@value='berry']"));
//如果次单选按钮处于未选中状态,则调用click方法选中此单选按钮
if (!radioOption.isSelected())
radioOption.click();
//断言属性值为"berry"的选项处于相中状态
Assert.assertTrue(radioOption.isSelected());
//查找name属性值为"fruit"的所有单选按钮对象,并存储到一个List容器中
List<WebElement> fruits = driver.findElements(By.name("fruit"));
/*使用for循环对List容器中的每个单选按钮进行遍历,查找value属性值为"watermelon"的单选按钮,如果查找到的此单选按钮处于选中状态,则调用click方法进行单击选择*/
for(WebElement fruit:fruits) {
if (fruit.getAttribute("value").equals("watermelon")) {
if(!fruit.isSelected())
fruit.click();
Thread.sleep(1000);
//断言单选按钮是否被成功选中
Assert.assertTrue(fruit.isSelected());
break;
}
}
}
@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}