继承LoadableComponent类可以在打开地址时,
判断浏览器是否打开了预期的网址,
需要重写load()与isLoad()方法;
即使没有定义get()方法,
也可以进行get()方法的调用,
get()方法会默认调用页面对象类中的load()方法。
import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.LoadableComponent; import org.testng.Assert; public class BaiduHomePage extends LoadableComponent<BaiduHomePage> { //百度首页的页面工厂 @FindBy(xpath = ".//*[@id='kw']") private WebElement inputBox; //输入框 @FindBy(xpath = ".//*[@id='su']") private WebElement searchButton; //搜索按钮 @FindBy(xpath = ".//*[@id='1']/h3/a") private WebElement encyclopedia; //中国_百度百科元素 private String baiduUrl = "https://www.baidu.com/"; //百度首页的地址 private String baiduOnce = "百度一下,你就知道"; //百度首页的标题 private WebDriver driver; public BaiduHomePage(){ //构造函数,生成浏览器对象,初始化PageFactory对象 System.setProperty("webdriver.firefox.marionette", "src/main/resourcec/geckodriver.exe"); driver = new FirefoxDriver(); PageFactory.initElements(driver, this); } @Override protected void load() { //打开百度 driver.get(baiduUrl); driver.manage().window().maximize(); } @Override protected void isLoaded() throws Error{ //断言浏览器是否打开了正确的网址 Assert.assertTrue(driver.getTitle().equals(baiduOnce)); } public void quit(){ //结束driver driver.quit(); } public void searchChina(){ //封装搜索“中国”的步骤 inputBox.sendKeys("中国"); //输入“中国” searchButton.click(); //点击搜索按钮 } public String getText(){ //封装获取中国_百度百科元素的文本 return encyclopedia.getText(); } }
import org.testng.Assert; import org.testng.annotations.Test; public class BaiduSearchCase { @Test //搜索“中国”的测试用例 public void baiduSearch() throws InterruptedException { BaiduHomePage baiduHomePage = new BaiduHomePage(); //生成一个BaiduHomePage对象实例 baiduHomePage.get(); baiduHomePage.searchChina(); Thread.sleep(2000); Assert.assertEquals(baiduHomePage.getText(), "中国_百度百科"); baiduHomePage.quit(); } }