在此实例中将以http://www.amazon.com/的查询功能来创建页面对象模型,让我们来看看如何在首页使用查询功能。
每个页面都提供了查询图书的功能。当查询提交后,返回一个新的相应的查询结果界面。
如何实现
1.创建一个HomePage类
package com.wiley.pageobjects;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
public class HomePage {
private static WebDriver driver;
//用来传递webdriver
public static WebDriver getDriver(){
return driver;
}
public HomePage(){
driver=new FirefoxDriver();
PageFactory.initElements(driver, this);
}
public void load(){
driver.get("http://www.amazon.com");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
public void close(){
driver.close();
}
public Search search(){
Search search=new Search();
return search;
}
}
2.创建一个Search类,主要用来提供查询的方法
package com.wiley.pageobjects;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Search {
//定位元素
@FindBy(id="twotabsearchtextbox")
private WebElement searchInputBox;
@FindBy(xpath="//input[@value='Go']")
private WebElement searchButton;
public Search(){
PageFactory.initElements(HomePage.getDriver(), this);
}
/**
* 输入查询内容的方法
* @param query
* @return
*/
public SearchResults searchInStore(String query){
searchInputBox.sendKeys(query);
searchButton.click();
return new SearchResults(query);
}
}
3.创建一个SearchResults类,提供得到查询结果的方法
package com.wiley.pageobjects;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;
public class SearchResults {
public SearchResults(String query) {
PageFactory.initElements(HomePage.getDriver(), this);
}
//得到查询结果
public List<String> getBooks(){
List<String> books=new ArrayList<String>();
List<WebElement> bookList=HomePage.getDriver()
.findElements(By.cssSelector("#s-results-list-atf > li"));
for (WebElement item : bookList) {
books.add(item.findElement(By.xpath("//*[@id='result_0']//h2")).getText());
}
return books;
}
}
4.创建查询功能的主测试方法
package com.wiley.pageobjects;
import static org.junit.Assert.*;
import org.junit.Test;
public class SearchTest {
@Test
public void testBookSearch(){
HomePage homePage=new HomePage();
homePage.load();
//查询"selenium webdriver in java"
SearchResults searchResult=homePage.search().searchInStore("selenium webdriver in java");
//验证查询结果
int totalCount=searchResult.getBooks().size();
//System.out.println(totalCount);
assertEquals(8,totalCount);
assertTrue(searchResult.getBooks().contains("Selenium Webdriver in Java: Learn With Examples"));
homePage.close();
}
}