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