被测试的HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form>
<input type = "checkbox" name = "fruit" value = "berry"/>草莓</input>
<br/>
<input type = "checkbox" name = "fruit" value = "watermelon"/>西瓜</input>
<br/>
<input type = "checkbox" name = "fruit" value = "orange"/>橙子</input>
</form>
</body>
</html>
完整代码:
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 OperateCheckbox {
WebDriver driver;
String baseUrl = "E:\\Coding\\JavaCode\\WebAutomationTest\\HTML\\Checkbox.html";
@BeforeMethod
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void testCheckbox() throws Exception {
driver.get(baseUrl);
Thread.sleep(1000);
//查找属性为"orange"的复选框元素
WebElement orangeCheckbox = driver.findElement(By.xpath("//input[@value='orange']"));
//如果此复选框处于未选中状态,则调用click方法选中此复选框
if (!orangeCheckbox.isSelected())
orangeCheckbox.click();
Thread.sleep(1000);
//断言属性值为"orange"的选项处于选中状态
Assert.assertTrue(orangeCheckbox.isSelected());
//如果复选框是选中状态,再次调用click方法单击取消复选框的选中状态
if(orangeCheckbox.isSelected())
orangeCheckbox.click();
Thread.sleep(1000);
//断言复选框处于非选中状态
Assert.assertFalse(orangeCheckbox.isSelected());
//查找所有name属性值为"fruit"的复选框,并存储到一个List容器中
List<WebElement> checkboxs = driver.findElements(By.name("fruit"));
/*使用for循环对List容器中的每个复选框进行遍历,并选中所有复选框*/
for(WebElement checkbox:checkboxs)
checkbox.click();
Thread.sleep(1000);
}
@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}