您的位置:首页 > 其它

Selenium-webdriver 页面模式在实际项目中的实际运用,大量Page页面如何初始化?

2013-09-23 12:49 447 查看
//编写页面类 封装页面属性和页面逻辑

package jd.pages.erp;

import jd.pages.Page;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.support.FindBy;

public class LoginPage extends Page

{

@FindBy(id= "Name")

public static WebElement username;

@FindBy(name= "Password")

public static WebElement userpwd;

@FindBy(name= "Logon")

public static WebElement loginBtn;

public static void Login(String user,String pwd)

{

username.sendKeys(user);

userpwd.clear();

userpwd.sendKeys(pwd);

loginBtn.click();

}

}

///在框架加载的时候就递归初始化某个包下面的所有 Page的子类,Page指的是一个自己编写Java类, 所有PageObject 页面都继承这个类, 下面在初始化页面的的时候就可以通过判断哪些页面该初始化,(通过判断是不是Page的子类) PS:因为webdriver中必须先加载页面才能访问页面内的元素,否则会报错, 单个的class可以用PageFactory.initElements(driver, (Class<?>) classObject);加载, 一旦页面元素多了, 就必须批量初始化。 所以采用递归的方式,一次性初始化所有Page,就不用每次使用某个页面都调用一次初始化方法了。

public static void initAllPages(WebDriver driver)

{

File rootFile = new File( Page.class.getResource(".").getFile());

//初始化所有子类

setSonList(rootFile, rootFile.getAbsolutePath() + "\\", Page.class, rootFile.getAbsolutePath() + "\\" ,driver);

}

public static <T> void setSonList(File rootFile, String parentDirectory, Class<T> parentClass, String mainPath ,WebDriver driver) {

if (rootFile.isDirectory()) {

File[] files = rootFile.listFiles();

for (File file : files) {

setSonList(file, parentDirectory, parentClass,mainPath, driver);

}

}

else {

String className = null;

try {

if (rootFile.getPath().indexOf(".class") != -1 ) {

className = rootFile.getPath().replace(mainPath, "").replace(".class", "").replace("\\", ".");

System.err.println("初始化Page:"+parentClass.getPackage().getName()+"."+className);

Class<?> classObject = Class.forName(parentClass.getPackage().getName()+"."+className);

classObject.asSubclass(parentClass);

PageFactory.initElements(driver, (Class<?>) classObject);

}

} catch (ClassNotFoundException e) {

System.err.println("找不到类 " + className);

} catch (ClassCastException e) {

System.err.println(className + " 不是 " + parentClass + " 的子类");

}

}

}

测试用例中组织业务逻辑;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐