页面对象模式(1)

页面对象模式介绍:

  页面对象模式是目前自动化测试领域普遍使用的设计模式之一,此模式可以大大提高测试代码的复用率,提高测试脚本的编写效率和维护效率

1.1使用PageFactory

测试网址:

https://mail.163.com/

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

(1)新建两个包分别存放对象类、测试类

LoginPage类的源代码

package cn.pageobject;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;

public class LoginPage {
    //使用FindBy注解,定位到需要操作的页面元素
    @FindBy(xpath="//input[@placeholder='邮箱帐号或手机号码']")
    public WebElement username;
    @FindBy(xpath="//input[@placeholder='输入密码']")
    public WebElement password;
    @FindBy(xpath="//a[@id='dologin']")
    public WebElement loginButton;
    public LoginPage(WebDriver driver){
        PageFactory.initElements(driver, this);
    }
}

Test163mail的源代码:

package cn.test;

import org.testng.annotations.Test;

import cn.pageobject.LoginPage;

import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;

public class Test163mail {
    WebDriver driver;
    String url ="https://mail.163.com/";
  @Test
  public void testLogin() throws InterruptedException {
      //生成一个LoginPage对象实例
      LoginPage loginpage = new LoginPage(driver);
      //进入登录框所在的frame,0代表第一个frame
      driver.switchTo().frame(0);
      //直接使用页面对象输入用户名
      loginpage.username.sendKeys("m17805983076");
      //直接使用页面对象输入密码
      loginpage.password.sendKeys("****");
      //直接使用页面对象单击登录
      loginpage.loginButton.click();
      //等待5秒
      Thread.sleep(5000);
      //断言登录后页面是否包含“未读邮件”关键字
      Assert.assertTrue(driver.getPageSource().contains("未读邮件"));
  }
  @BeforeMethod
  public void beforeMethod() {
      System.setProperty("webdriver.chrome.driver", "D:\\WebDriver\\chromedriver_win32\\chromedriver.exe");
      driver = new ChromeDriver();
      driver.manage().window().maximize();
      driver.get(url);
  }

  @AfterMethod
  public void afterMethod() {
      driver.quit();
  }

}

猜你喜欢

转载自www.cnblogs.com/z-zzz/p/10565923.html
今日推荐