WebDriver为了支持PageObject模式,内置了一个PageFactory的工厂类。接下来本文通过一个案例来讲下如何使用PageFactory。
首先定义一个PageObject下面这个Class定义了一个页面对象通过工厂的方式将目标页面上的元素都定义好并且定义了一个当前页面的一个执行步骤【关键词搜索】
package cn.testfan; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class BaiduSearchPage { @FindBy(id="kw") private WebElement a; @FindBy(id="su") private WebElement b; public void searchKeyWords(String text) { a.sendKeys(text); b.click(); } }
为了保证上述代码能运行不报空指针我们需要实例化这个PageObject写一个测试类的Class如下
package cn.testfan; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.PageFactory; public class TestBaiduWithPageFactory { public static void main(String[] args) throws InterruptedException { WebDriver driver = new FirefoxDriver(); driver.get("http://www.baidu.com/"); driver.manage().window().maximize(); BaiduSearchPage page = PageFactory.initElements(driver, BaiduSearchPage.class); page.searchKeyWords("testfan");
Thread.sleep(1500); System.out.println(driver.getTitle()); driver.close(); } }
这样以后当页面元素发生变化的时候就不需要去改你的case了只需要去变更对应的PageObject中工厂定义就可以了。
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!