PageObject模式实现页面元素分离

Page Object模式

Page Object将测试对象及单个的测试步骤封装在每个Page对象中,以page为单位进行管理。

1、例如没有使用Page Object模式时对于163邮箱的登录操作代码如下:

packagecom.test;

 

importorg.openqa.selenium.By;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

 

publicclasstest163 {

   publicstaticvoidmain(String[] args)

 {

      //启动浏览器,进入163邮箱首页

      WebDriver driver =newFirefoxDriver();

      driver.get("http://mail.163.com/");

      

      Thread.sleep(5000);

      //输入用户名密码,登录邮箱

      WebElement youxiangzhanghao_element = driver.findElement(By.id("idInput"));

      youxiangzhanghao_element.clear();

  

       youxiangzhanghao_element.sendKeys("justForYourTesting");

       

       WebElement mima_element = driver.findElement(By.id("pwdInput"));

       mima_element.sendKeys("135135");

               

       WebElement denglu_element = driver.findElement(By.id("loginBtn"));

       denglu_element.click();

       

       Thread.sleep(10000);

      

       driver.close();

   }

}

2、使用FindBy注解

package com.mail163;

 

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.FindBy;

 

public class mail163 {

      @FindBy(id="idInput" )

      private WebElement username;

 

      @FindBy(id="pwdInput" )

      private WebElement password;

 

      @FindBy(id="loginBtn" )

      private WebElement loginBtn;

 

      public void login(WebDriver dr,String username,String pwd){

             dr.get("http://mail.163.com");

             this.username.sendKeys(username);

             this.password.sendKeys(password);

            loginBtn.click();

      }

}

通过FindBy每一个页面元素都被定义为一个类中的私有变量,通过调用login()方法即可实现登陆页面的登录操作。

    通过对比1、2明显可以看出,2的逻辑结果比1更加简洁,以每个page为单位(类),以每个page元素为类的属性,以方法login()来实现每个页面元素操作的封装。程序的逻辑独立性更强,也方便后期的维护和修改。

3、对Login类的login方法的初始化

package com.test.java;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;

public class testLogin3 {
    public void login1(String username, String password)
    {
    WebDriver driver= new FirefoxDriver();
    // 对页面元素的初始化
    login m=PageFactory.initElements(driver, login.class);
    m.login(driver, username, password);
    }
   
    public static void main(String[] args)
    {
        testLogin3 tl = new testLogin3();
        tl.login1("justForYourTesting","135135");
    }
}

转载于:https://www.cnblogs.com/NextHop/p/4918103.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值