当前位置: 代码迷 >> Web前端 >> Selenium-webdriver 页面模式在实际项目中的实际运用,大量Page页面怎么初始化
  详细解决方案

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

热度:973   发布时间:2013-09-28 10:01:20.0
Selenium-webdriver 页面模式在实际项目中的实际运用,大量Page页面如何初始化?

//编写页面类  封装页面属性和页面逻辑

 

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 + " 的子类");
            }
        }
    }

测试用例中组织业务逻辑;

  相关解决方案