5.如何將自動化工程從Selenium1.0遷移到Selenium2.0
已經(jīng)在Selenium1.0上構(gòu)建測試工程的用戶,我們?yōu)槟峁┝艘环葜笇?dǎo)如何將已有的代碼遷移到Selenium2.0。Selenium2.0的首席開發(fā)工程師Simon Stewart為此撰寫了一片文章:Magrating From Selenium RC to Selenium WebDriver。
6.Selenium-WebDriver API簡介
WebDriver可以用來實現(xiàn)Web應(yīng)用程序的自動化測試,特別適合于驗證實際結(jié)果是否符合預(yù)期結(jié)果的場景。WebDriver旨在提供比 Selenium1.0更加易用、友好的API,便于用戶的探索和理解,從而使測試用例變得容易閱讀和維護(hù)。WebDriver沒有使用任何第三方測試框架,所以它可以很好與單元測試工具或者古老的main函數(shù)結(jié)合使用。本章節(jié)將介紹如何使用WebDriver的API,幫助你慢慢開始了解 WebDriver。如果你還沒有新建一個Selenium工程,請先完成這個操作,在這個章節(jié)的上面有詳細(xì)的描述。
當(dāng)你創(chuàng)建完Selenium工程后,你會發(fā)現(xiàn)WebDriver和普通的第三方庫一樣是完全獨(dú)立的,在你使用之前不需要啟動任何額外的進(jìn)程或者安裝程序,相反如果你使用Selenium-RC需要先啟動代理服務(wù)器。
注意:當(dāng)你使用如下WebDriver時需要額外的步驟:Chrome Driver,Opera Driver,Android Driver,IPhone Driver。
現(xiàn)在你肯定躍躍欲試要寫一些代碼了。我們以一個簡單的例子來開始第一段旅程:在Google上搜索“Cheese”,并打印出搜索結(jié)果網(wǎng)頁的標(biāo)題。
package org.openqa.selenium.example;
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.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Selenium2Example {
public static void main(String[] args) {
// 創(chuàng)建一個FirefoxDriver實例
// 這個類依賴于接口而不是接口的實現(xiàn)
WebDriver driver = new FirefoxDriver();
// 使用get方法訪問Google
driver.get("http://www.google.com");
// 使用下面這個方法也能夠達(dá)到訪問Google的目的
// driver.navigate().to("http://www.google.com");
// 找到html輸入框的name
WebElement element = driver.findElement(By.name("q"));
// 輸入要查找的內(nèi)容
element.sendKeys("Cheese!");
// 提交表單,WebDriver會自動找到我們需要提交的元素所在的表單
element.submit();
// 打印網(wǎng)頁的標(biāo)題
System.out.println("Page title is: " + driver.getTitle());
// Google的搜索網(wǎng)頁會通過JS動態(tài)渲染
// 等待頁面加載完畢,超時時間為10秒
(new WebDriverWait(driver, 10)).until(new ExpectedCondition() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
}
});
// 控制臺上將打印如下信息: "cheese! - Google Search"
System.out.println("Page title is: " + driver.getTitle());
// 關(guān)閉瀏覽器
driver.quit();
}
}
在本章節(jié)的接下來篇幅,我們將學(xué)習(xí)如何使用WebDriver操作你的瀏覽器,如何使用框架和窗口來測試Web網(wǎng)站。當(dāng)然,我們將提供更加翔實的論述和舉例。