自動化測試如何處理ComboBox的值?

自動化測試如何處理ComboBox的值?

ComBox Month

 

 

這篇文章主要說明自動化測試程式如何選取這樣 comboBox的值?

ComboBox是很常見的網頁元件,就像選擇題一樣選取下拉式內的值,常見的像是月份、時間等

如果是用自動化測試程式執行時要如何選取其中一個值呢?

這篇文章用FaceBook為例子,最後用Selenium/Java實作說明

測試情境

1. 瀏覽 www.Facebook.com網站

2. Birthday中,有12個月分的選項

3. 選擇 Jan

Combox Value

程式說明

 

用FireBug分析網頁,該月份的 Xpath = //*[@id=’month’]

另外,每個 option 都定義有 value,例如 Value = 1為  “Jan”

因此對於 Selenium來說,就可以運用 Value = “1” 或是畫面顯示的文字 Jan選取預期的選項

combox_Facebook

 

Selenium有三個方法

分別是 by visible Text 也就是畫面上看到的文字。

//select by visible text
drpMonth.selectByVisibleText(“Jan”);

By Index 選項的陣列順序。起始值為 1

//select by index
drpMonth.selectByIndex(1);

By Value ,這裡的 Value  指的是 HTML中定義的 Value

 

//select by value
drpMonth.selectByValue(“1”);

Java/Selenium程式範例

[pastacode lang=”java” message=”” highlight=”” provider=”manual”]

package mySelenium;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;


public class comboBox_facebook {

	public static void main(String[] args) {
		
		WebElement SelectedItem =null;
		WebDriver driver = new FirefoxDriver();
		driver.get("https://www.facebook.com/");
		driver.manage().window().maximize();
		Select drpMonth = new Select(driver.findElement(By.xpath("//*[@id='month']")));
		
		
		//select by visible text
		drpMonth.selectByVisibleText("Jan");
		SelectedItem = drpMonth.getFirstSelectedOption();
		System.out.println("Select by Text Jan: " + SelectedItem.getText());
		
		//select by index
		drpMonth.selectByIndex(1);
		SelectedItem = drpMonth.getFirstSelectedOption();
		System.out.println("Select by index 1: " + SelectedItem.getText());
		
		//select by value
		drpMonth.selectByValue("1");
		SelectedItem = drpMonth.getFirstSelectedOption();
		System.out.println("select by Value 1: " + SelectedItem.getText());
		
		//print all values from drop down
        List<WebElement> theseOptions = drpMonth.getOptions();
	    for(WebElement option:theseOptions){
	      System.out.print(option.getText() + ": ");
	    } 
	    
	    // Close the browser
	    driver.quit();
	}

}

[/pastacode]

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *