自動化測試工具 Selenium WebDriver 入門教程
這里只記錄學習 Selenium WebDriver 的過程,尤其是運行時可能出現的問題,學習 java 與 Selenium WebDriver 配合的方法。
一、下載文件
先要去官網(http://seleniumhq.org/download/)下載必需的文件:
- Selenium IDE (專門用于 FireFox 測試的獨立界面,可以錄制測試步驟,但我更傾向于寫代碼做標準的功能測試)
- Selenium Server (可以輸入指令控制、可以解決跨域的 js 問題,等到后面學到了再講吧)
- The Internet Explorer Driver Server (專門用于IE測試的)
- Selenium Client Drivers (可以找到你熟悉的語言,例如我選擇的 Java)
- Third Party Browser Drivers NOT SUPPORTED/DEVELOPED by seleniumhq(第三方開發的 Selenium 插件,第一個就是 Chrome 的,否則你就沒辦法測試 Chrome 了)
- 其他的,就根據你自己的需要尋找吧,目前這些足夠我用了。 </ul>
二、安裝 & 運行
貌似擺弄新東西時,只有 “Hello World” 蹦出來以后,我們這些初學者才會感到情緒穩定,那就趕緊開始吧。
對于初期打算直接用編程方式制作測試用例的情況來說,Selenium IDE、Selenium Server 都可以不用安裝執行。
英語好的朋友可以直接看官網的文檔(http://seleniumhq.org/documentation/)就能夠開始使用了。
看中文的,就繼續聽我嘮叨:
【1. 建立 Maven 工程】
Selenium 支持 maven 工程,這會讓你的工作更加簡便。
用 Eclipse 建個 Maven 的工程,建成后,直接修改 pom.xml,(參考:http://seleniumhq.org/docs/03_webdriver.html#setting-up-a-selenium-webdriver-project)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Selenium2Test</groupId> <artifactId>Selenium2Test</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.25.0</version> </dependency> <dependency> <groupId>com.opera</groupId> <artifactId>operadriver</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>com.opera</groupId> <artifactId>operadriver</artifactId> <version>0.16</version> <exclusions> <exclusion> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-remote-driver</artifactId> </exclusion> </exclusions> </dependency> </dependencies> </dependencyManagement> </project>
pom.xml 修改保存后,eclipse 會自動把需要的 jar 包下載完成。
【2. 測試 FireFox】
Selenium 最初就是在 FireFox 上做起來的插件,所以我們先來搭建 FireFox 的環境。
確保你正確安裝了 FireFox 后,就可以直接編寫 java 代碼測試嘍。
在 lesson1 目錄下建立 ExampleForFireFox.java
(因為國內不少朋友訪問 google 的時候會出問題,所以我就把代碼中的 google 變成 baidu 了)
package lesson1;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 ExampleForFireFox { public static void main(String[] args) { // 如果你的 FireFox 沒有安裝在默認目錄,那么必須在程序中設置 // System.setProperty("webdriver.firefox.bin", "D:\Program Files\Mozilla Firefox\firefox.exe"); // 創建一個 FireFox 的瀏覽器實例 WebDriver driver = new FirefoxDriver();
// 讓瀏覽器訪問 Baidu driver.get("http://www.baidu.com"); // 用下面代碼也可以實現 // driver.navigate().to("http://www.baidu.com"); // 獲取 網頁的 title System.out.println("1 Page title is: " + driver.getTitle()); // 通過 id 找到 input 的 DOM WebElement element = driver.findElement(By.id("kw")); // 輸入關鍵字 element.sendKeys("zTree"); // 提交 input 所在的 form element.submit(); // 通過判斷 title 內容等待搜索頁面加載完畢,間隔10秒 (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().toLowerCase().endsWith("ztree"); } }); // 顯示搜索結果頁面的 title System.out.println("2 Page title is: " + driver.getTitle()); //關閉瀏覽器 driver.quit(); }
}</pre>
普通情況下,直接運行代碼就可以看到會自動彈出 FireFox 窗口,訪問 baidu.com,然后輸入關鍵字并查詢,一切都是自動完成的。
錯誤提醒:
1)Exception in thread "main" org.openqa.selenium.WebDriverException: Cannot find firefox binary in PATH. Make sure firefox is installed.</span>
出現這個錯誤,是說明你的 FireFox 文件并沒有安裝在默認目錄下,這時候需要在最開始執行:System.setProperty 設置環境變量 "webdriver.firefox.bin" 將自己機器上 FireFox 的正確路徑設置完畢后即可。
2)Exception in thread "main" org.openqa.selenium.UnsupportedCommandException: Bad request</span>出現這個錯誤,很有意思。 查了一下 有人說應該是 hosts 出現了問題,加上一個 127.0.0.1 localhost 就行了,但我的 hosts 上肯定有這個玩意,為啥也會出現這個問題呢?
經過調試,發現 127.0.0.1 localhost 的設置必須要在 hosts 文件的最開始,而且如果后面有其他設置后,也不要再出現同樣的 127.0.0.1 localhost ,只要有就會出錯。(因為我為了方便訪問 google 的網站,專門加入了 smarthosts 的內容,導致了 localhost 的重復)
【3. 測試 Chrome】
Chrome 雖然不是 Selenium 的原配,但是沒辦法,她太火辣了,絕對不能拋下她不管的。
把 ExampleForFireFox.java 稍微修改就可以制作出一個 ExampleForChrome.java ,直接把 new FireFoxDriver() 修改為 new ChromeDriver() 你會發現還是行不通。
錯誤如下:
1)Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromedriver/downloads/list</span>
這應該是找不到 chrome 的文件,好吧,利用 System.setProperty 方法添加路徑,這里要注意,是 “webdriver.chrome.driver” 可不是“webdriver.chrome.bin”</span>
設置路徑后還是會報錯:
2)[6416:4580:1204/173852:ERROR:gpu_info_collector_win.cc(91)] Can't retrieve a valid WinSAT assessment.</span>
這個貌似是因為 Selenium 無法直接啟動 Chrome 導致的,必須要通過前面咱們下載 Chrome 的第三方插件 ChromeDriver,去看第一個錯誤中提示給你的 網址:http://code.google.com/p/selenium/wiki/ChromeDriver
按照人家給的例子來修改我們的測試代碼吧:
package lesson1;import java.io.File; import java.io.IOException;
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait;
public class ExampleForChrome { public static void main(String[] args) throws IOException { // 設置 chrome 的路徑 System.setProperty( "webdriver.chrome.driver", "C:\Documents and Settings\sq\Local Settings\Application Data\Google\Chrome\Application\chrome.exe"); // 創建一個 ChromeDriver 的接口,用于連接 Chrome @SuppressWarnings("deprecation") ChromeDriverService service = new ChromeDriverService.Builder() .usingChromeDriverExecutable( new File( "E:\Selenium WebDriver\chromedriver_win_23.0.1240.0\chromedriver.exe")) .usingAnyFreePort().build(); service.start(); // 創建一個 Chrome 的瀏覽器實例 WebDriver driver = new RemoteWebDriver(service.getUrl(), DesiredCapabilities.chrome());
// 讓瀏覽器訪問 Baidu driver.get("http://www.baidu.com"); // 用下面代碼也可以實現 // driver.navigate().to("http://www.baidu.com"); // 獲取 網頁的 title System.out.println("1 Page title is: " + driver.getTitle()); // 通過 id 找到 input 的 DOM WebElement element = driver.findElement(By.id("kw")); // 輸入關鍵字 element.sendKeys("zTree"); // 提交 input 所在的 form element.submit(); // 通過判斷 title 內容等待搜索頁面加載完畢,間隔10秒 (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().toLowerCase().endsWith("ztree"); } }); // 顯示搜索結果頁面的 title System.out.println("2 Page title is: " + driver.getTitle()); // 關閉瀏覽器 driver.quit(); // 關閉 ChromeDriver 接口 service.stop(); }
}</pre>
運行一下看看,是不是一切OK了?
補充:仔細看了一下官網的介紹:Chrome Driver is maintained / supported by the Chromium project iteslf. 看來如果使用 new ChromeDriver() 的話,應該要安裝 Chromium 而不是 Chrome,我現在懶得折騰了,有興趣的童鞋可以試驗一下。
【4. 測試 IE】
想逃避 IE 嗎?? 作為前端開發,IE 你是必須要面對的,沖吧!
其實你會發現, Selenium 主要也就是針對 FireFox 和 IE 來制作的,所以把 FireFox 的代碼修改為 IE 的,那是相當的容易,只需要簡單地兩步:
1)把 ExampleForFireFox.java 另存為 ExampleForIE.java
2)把 WebDriver driver = new FirefoxDriver(); 修改為 WebDriver driver = new InternetExplorerDriver();
3)一般大家的 IE都是默認路徑吧,所以也就不用設置 property 了
package lesson1;import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait;
public class ExampleForIE { public static void main(String[] args) { // 如果你的 FireFox 沒有安裝在默認目錄,那么必須在程序中設置 // System.setProperty("webdriver.firefox.bin", "D:\Program Files\Mozilla Firefox\firefox.exe"); // 創建一個 FireFox 的瀏覽器實例 WebDriver driver = new InternetExplorerDriver();
// 讓瀏覽器訪問 Baidu driver.get("http://www.baidu.com"); // 用下面代碼也可以實現 // driver.navigate().to("http://www.baidu.com"); // 獲取 網頁的 title System.out.println("1 Page title is: " + driver.getTitle()); // 通過 id 找到 input 的 DOM WebElement element = driver.findElement(By.id("kw")); // 輸入關鍵字 element.sendKeys("zTree"); // 提交 input 所在的 form element.submit(); // 通過判斷 title 內容等待搜索頁面加載完畢,間隔10秒 (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().toLowerCase().endsWith("ztree"); } }); // 顯示搜索結果頁面的 title System.out.println("2 Page title is: " + driver.getTitle()); // 關閉瀏覽器 driver.quit(); }
}</pre>
運行一下,是不是 so easy?
入門工作完成,現在完全可以利用 java 代碼,讓 Selenium 自動執行我們設置好的測試用例了,不過.....這僅僅是個開始。