为什么要使用page-object
? 集中管理元素对象
? 集中管理一个page内的公共方法
? 后期维护方便
集中管理元素对象
? 实现方法:
1 public static By input = By.xpath("//input[@type=‘text‘]"); 2 public static By check = By.xpath("//input[@type=‘checkbox‘]");
? 调用方法:
WebElement element = driver.findElement(Test7.input);
Page类的实现
? 目的:
有了page类后,在具体的脚本中,要用到哪个page,就new这个page的对象,然后调用里面的公共方法即可
? 实现方法:
1 public class Page{ 2 protected WebDriver Driver; 3 public Page(WebDriver Driver) 4 { 5 this.Driver=Driver; 6 } 7 8 private boolean waitToDisplayed(final By key){ 9 boolean waitToDisplayed=new WebDriverWait(Driver,10).until(new ExpectedCondition<Boolean>(){ 10 public Boolean apply(WebDriver d){ 11 return d.findElement(key).isDisplayed(); 12 } 13 }); 14 return waitToDisplayed; 15 } 16 17 18 protected WebElement getElement(By key){ 19 WebElement element=null; 20 if(this.waitToDisplayed(key)){ 21 element=Driver.findElement(key); 22 } 23 return element; 24 } 25 }
? 说明:
Page类是一个基础类,其它的Page类都要继承该类,比如:
1 public class DemoPage extends Page { 2 3 public static By input = By.xpath("//input[@type=‘text‘]"); 4 public static By check = By.xpath("//input[@type=‘checkbox‘]"); 5 public static By radio = By.xpath("//input[@type=‘radio‘]"); 6 public static By action = By.xpath("//*[@id=‘action‘]/input"); 7 public static String iframe = "in"; 8 9 10 public DemoPage(WebDriver Driver) 11 { 12 super(Driver); 13 } 14 15 public void input(WebDriver Driver,String message){ 16 WebElement element=this.getElement(input); 17 element.sendKeys(message); 18 } 19 20 public void input_clear(WebDriver Driver){ 21 WebElement element=this.getElement(input); 22 element.clear(); 23 } 24 25 }
在具体的脚本中的使用方法:
1 public class day7Test { 2 private WebDriver Driver; 3 @Test 4 public void RobotFream() { 5 DemoPage dp=new DemoPage(Driver); 6 dp.input(Driver, "i love yuezi"); 7 dp.input_clear(Driver); 8 } 9 @BeforeClass 10 public void beforeClass() { 11 System.setProperty("webdriver.firefox.bin", "D:/Mozilla Firefox/firefox.exe"); 12 Driver=new FirefoxDriver(); 13 Driver.manage().window().maximize(); 14 Driver.navigate().to("file:///C:/Users/zhanghm/Desktop/Alert.html"); 15 16 } 17 18 @AfterClass 19 public void afterClass() { 20 Driver.close(); 21 Driver.quit(); 22 } 23 24 }
Page-object的优点
- 脚本代码更加整洁
- 可读性更高
- 维护方便
时间: 2024-10-25 10:15:51