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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值