網站自動化教學課程:Selenium如何處理網頁的checkBox
這篇文章主要說明如何用Selenium/Java處理網頁的CheckBox。
CheckBox 有一個特有的屬性來得知該CheckBox是否已經點選,最後用一個完整的Java程式範例執行。
測試情境
http://www.w3schools.com/html/tryit.asp?filename=tryhtml_checkbox
這個網站中,右手邊的 iFrame有兩個 checkBox,我們要做的自動化測試為
1. 找到右手邊 Bike 的checkBox
2. 印出該checkBox的相關屬性,例如,是否已經被勾選?
3. 點擊該checkBox
2. 印出該checkBox的相關屬性,是否已經被勾選?
程式說明
要如何知道該checkBox是否已經被點選? 我們主要運用isSelected()來得知。
driver.findElement(By.xpath(bike_ChkBox_Xpath)).isSelected()
完整程式碼範例
[pastacode lang=”java” message=”Selenium CheckBox handling” highlight=”” provider=”manual”]
package mySelenium;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class checkBox {
WebDriver driver;
@Before
public void setUp()
{
driver = new FirefoxDriver();
driver.get("http://www.w3schools.com/html/tryit.asp?filename=tryhtml_checkbox");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Test
public void testRadio(){
// Locate the iframe first
driver.switchTo().defaultContent(); // you are now outside both frames
driver.switchTo().frame("iframeResult");
String bike_ChkBox_Xpath = "//input[@value='Bike']";
System.out.println("****before click the Male Radio");
System.out.println("The Output of the IsSelected " + driver.findElement(By.xpath(bike_ChkBox_Xpath)).isSelected());
System.out.println("The Output of the IsEnabled " + driver.findElement(By.xpath(bike_ChkBox_Xpath)).isEnabled());
System.out.println("The Output of the IsDisplayed " + driver.findElement(By.xpath(bike_ChkBox_Xpath)).isDisplayed());
//Click the checkBox "I have a bike"
driver.findElement(By.xpath("//input[@value='Bike']")).click();
System.out.println("****after click the checkBox");
System.out.println("The Output of the IsSelected " + driver.findElement(By.xpath(bike_ChkBox_Xpath)).isSelected());
System.out.println("The Output of the IsEnabled " + driver.findElement(By.xpath(bike_ChkBox_Xpath)).isEnabled());
System.out.println("The Output of the IsDisplayed " + driver.findElement(By.xpath(bike_ChkBox_Xpath)).isDisplayed());
}
@After
public void teadDown()
{
//Close the current window, quitting the browser
driver.close();
//Quits this driver, closing every associated window that was open.
driver.quit();
}
}
[/pastacode]