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