Java语言搭建Web自动化框架学习六(封装+继承)

本文介绍了如何通过在pageobject包中创建BasePage基类来封装页面共性操作,如等待元素、点击和输入等,从而减少代码冗余。LoginPage和其他功能页面继承BasePage,直接调用封装好的方法。同时,建立了一个testdatas包,用于存储测试数据相关类,如Constant类,保存测试地址等常量。这一改进提高了代码复用性和维护性。

核心代码

6.1在pageobject包中新建一个BasePage类,把页面共性(等待元素、点击、输入等页面元素操作)抽取出来

public class BasePage {
	
	//等待元素可见
	public WebElement waitElementVisible(By by) {
		WebDriverWait webDriverWait = new WebDriverWait(WebDriverUtils.driver,5);
		WebElement webElement = webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(by));
		return webElement;
	}
	
	//等待元素可点击
	public WebElement waitElementClickable(By by) {
		WebDriverWait webDriverWait = new WebDriverWait(WebDriverUtils.driver,5);
		WebElement webElement = webDriverWait.until(ExpectedConditions.elementToBeClickable(by));
		return webElement;
	}
	
	//点击元素
	public void click(By by) {
		waitElementClickable(by).click();
		//TODO预留,比如打印日志	
	}
	//输入数据
	public void type(By by,String inputData) {
		waitElementVisible(by).sendKeys(inputData);
		//TODO预留,比如打印日志	
	}
}

6.2修改LoginPage类,其他功能页面都继承BasePage,直接使用BasePage封装好的方法,减少冗余代码

	public void input_loginName(String loginName) {
		type(loginNameBy, loginName);
	}
	
	public void input_loginPwd(String loginPwd) {
		type(loginPwdBy, loginPwd);
	}
	
	public void Click_loginBtn() {
		click(loginBtnBy);
	}

6.3新建一个testdatas包,专门保存测试数据相关的类

在包里新建一个Constant类,测试地址等常量保存在该类中

public class Constant {
	//一般常量用大写
	public static final String LOGIN_URL = "登录测试地址url";
	public static final String INDEX_URL = "登录成功后跳转的主页测试地址url";
}

6.4其他类使用地址的代码行同步替换:

WebDriverUtils.driver.get(Constant.LOGIN_URL);