页面对象(page object)模式

页面对象模式简介

使用页面对象的设计模式。页面对象模型将测试代码和被测试的页面的页面元素及其操作方法进行分离,以降低页面元素的变化对测试代码的影响。每一个被测试的页面都会被定义为一个类,类中会定位所有需进行测试操作的页面元素对象,并且定义操作每一个页面元素对象的方法。
如果用户没有使用此模式,那么奖登录过程都用相同的代码段实现,如果在测试的过程中需要多次操作登录,那么只能复制相同的代码来简化编写工作,但是可怕的是一旦页面元素发生一点点变化,那么测试人员需求人工的把所有的涉及变化的逻辑一一修改,会在不同的测试代码中进行搜索和页面修改,这样大大的增加了工作量,很容易出现修改错误。

使用PageFactory类给测试类提供待操作页面元素

首先创建LoginObject类

import org.openqa.selenium.WebDriver;
        import org.openqa.selenium.WebElement;
        import org.openqa.selenium.support.FindBy;
        import org.openqa.selenium.support.PageFactory;
public class LoginObject {
       @FindBy(xpath="/html/body/div/div/div[2]/div/div[2]/div[1]/input")
    public WebElement username;
    @FindBy(xpath="/html/body/div/div/div[2]/div/div[2]/div[2]/input")
    public WebElement pwd;
    @FindBy(xpath="/html/body/div/div/div[2]/div/div[2]/input")
    public WebElement loginButton;
    public  LoginObject(WebDriver driver){
        PageFactory.initElements(driver,this);
    }
}

然后再创建LoginObjectTest类

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class LoginObjectTest {
    private WebDriver driver;
    @BeforeClass
    public void BeforeTest() {
        System.setProperty("webdriver.firefox.bin", "D:\\wylsoft\\Firefox\\firefox.exe");
        System.setProperty("webdriver.gecko.driver", "D:\\wylsoft\\selenium3.5\\geckodriver.exe");
        driver = new FirefoxDriver();
        driver.get("http://192.168.109.181:8085");
        driver.manage().window().maximize();
    }
    @Test
    public void login() throws InterruptedException {
       LoginObject loginO=new LoginObject(driver);
       loginO.username.sendKeys("admin");
       loginO.pwd.sendKeys("admin");
       loginO.loginButton.click();
    }
    @AfterTest
    public void afterTest() {
        // driver.close();//关闭浏览器
        System.out.println("测试完成啦");
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值