第1章 入门
1.1 下载selenium2.0的lib包
http://code.google.com/p/selenium/downloads/list
官方UserGuide:http://seleniumhq.org/docs/
1.2 用webdriver打开一个浏览器
我们常用的浏览器有firefox和IE两种,firefox是selenium支持得比较成熟的浏览器。但是做页面的测试,速度通常很慢,严重影响持续集成的速度,这个时候建议使用HtmlUnit,不过HtmlUnitDirver运行时是看不到界面的,对调试就不方便了。使用哪种浏览器,可以做成配置项,根据需要灵活配置。
- 打开firefox浏览器:
//Create a newinstance of the Firefox driver
WebDriver driver = newFirefoxDriver();
- 打开IE浏览器
//Create a newinstance of the Internet Explorer driver
WebDriver driver = newInternetExplorerDriver ();
- 打开HtmlUnit浏览器
//Createa new instance of the Internet Explorer driver
WebDriverdriver = new HtmlUnitDriver();
1.3 打开测试页面
对页面对测试,首先要打开被测试页面的地址(如:http://www.google.com),web driver 提供的get方法可以打开一个页面:
// And now use thedriver to visit Google
driver.get("http://www.google.com");
1.4 GettingStarted
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 voidmain(String[] args) {
// Create a newinstance of the Firefox driver
// Notice that theremainder of the code relies on the interface,
// not the implementation.
WebDriver driver = newFirefoxDriver();
// And now use this tovisit Google
driver.get("http://www.google.com");
// Alternatively thesame thing can be done like this
// driver.navigate().to("http://www.google.com");
// Find the text inputelement by its name
WebElement element =driver.findElement(By.name("q"));
// Enter something tosearch for
element.sendKeys("Cheese!");
// Now submit the form.WebDriver will find the form for us from the element
element.submit();
// Check the title ofthe page
System.out.println("Page title is: " + driver.getTitle());
// Google's search isrendered dynamically with JavaScript.
// Wait for the pageto load, timeout after 10 seconds
(newWebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Booleanapply(WebDriver d) {
returnd.getTitle().toLowerCase().startsWith("cheese!");
}
});
// Should see:"cheese! - Google Search"
System.out.println("Page title is: " + driver.getTitle());
//Close the browser
driver.quit();
}
}
第2章 Webdirver对浏览器的支持
2.1 HtmlUnit Driver
优点:HtmlUnit Driver不会实际打开浏览器,运行速度很快。对于用FireFox等浏览器来做测试的自动化测试用例,运行速度通常很慢,HtmlUnit Driver无疑是可以很好地解决这个问题。
缺点:它对JavaScript的支持不够好,当页面上有复杂JavaScript时,经常会捕获不到页面元素。
使用:
WebDriver driver = new HtmlUnitDriver();
2.2 FireFox Driver
优点:FireFox Dirver对页面的自动化测试支持得比较好,很直观地模拟页面的操作,对JavaScript的支持也非常完善,基本上页面上做的所有操作FireFox Driver都可以模拟。
缺点:启动很慢,运行也比较慢&#