先来看下,用普通的方法如何进行webdrviver的测试
public class SimpleAmazonSearchTest {
private FirefoxDriver driver;
@Before
public void setupSelenium() {
driver = new FirefoxDriver();
}
@After
public void closeSelenium() {
driver.close();
driver.quit();
}
@Test public void
search_amazon() {
driver.get("http://www.amazon.co.uk/");
WebElement keywordsField = driver.findElement(By.name("field-keywords"));
keywordsField.sendKeys("iain banks");
WebElement goButton = driver.findElement(By.cssSelector("#navGoButton input"));
goButton.click();
WebElement topResultTitle = driver.findElement(By.cssSelector("#result_0 .title a"));
assertThat(topResultTitle.getText(), is("Stonemouth"));
}
很明显,上述代码中,测试代码和被测试代码之间耦合了。如果被测试的页面本身改变了的话,那么必须改变的代码很多,因此,可以抽象出被测试代码的“定义”部分,比如:
public class AmazonHomePage {
public static AmazonHomePage navigateTo(WebDriver driver);
public AmazonSearchResultsPage searchFor(String searchTerm);
}
上面的是要在主页中寻找代码的主类,测试的目的是输入搜索结果后,
最后的结果页面,也就是可以用AmazonSearchResultsPage这个类去封装
public class AmazonSearchResultsPage {
public String getTopResultTitle();
}
假设结果页面中,就只是获得页面的标题而已。
接下来是测试代码的框架:
AmazonHomePage homePage = AmazonHomePage.navigateTo(driver);
AmazonSearchResultsPage resultsPage =
homePage.searchFor("iain banks");
assertThat(resultsPage.getTopResultTitle(), is("Transition"));
可以看到,在测试代码中,没有了和XPATH等相关的,一切需要“寻找元素”之类的东西,这样,如果页面发生变化的话,改页面类本身就可以了,不需要更改测试代码
接下来,分别丰富两个类的代码,首先是在主页中,用注解的方式去寻找元素
public class AmazonHomePage {
private WebDriver driver;
@FindBy(name="field-keywords")
private WebElement keywordsField;
@FindBy(css="#navGoButton input")
private WebElement goButton;
public AmazonHomePage(WebDriver driver) {
this.driver = driver;
}
public AmazonSearchResultsPage searchFor(String searchTerm) {
keywordsField.sendKeys(searchTerm);
goButton.click();
return PageFactory.initElements(driver, AmazonSearchResultsPage.class);
}
public static AmazonHomePage navigateTo(WebDriver driver) {
driver.get("http://www.amazon.co.uk/");
return PageFactory.initElements(driver, AmazonHomePage.class);
}
public class AmazonSearchResultsPage {
private WebDriver driver;
@FindBy(css="#result_0 .title a")
private WebElement topResultTitle;
public AmazonSearchResultsPage(WebDriver driver) {
this.driver = driver;
}
public String getTopResultTitle() {
return topResultTitle.getText();
}
上面使用的就是selenium 2中的pageobject的设计模式了