Selenium框架源码解析-1 PageFactory

Selenium框架源码解析-1 PageFactory

前提:
几天前接触到Selenium,看到定义的变量不需要实例化就可以直接运行,觉得挺稀奇,故想一览其中之奥妙,取其中之精华。


直接上码:

package com.prs.t;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.PageFactory;

public class LoginPage {
    private WebDriver webdriver;

    public  WebElement su;
    public  WebElement kw;
    public LoginPage(WebDriver webdriver){
        this.webdriver = webdriver;
        PageFactory.initElements(webdriver, this);
    }
    public void inputAndClickSerch() throws InterruptedException{
        kw.sendKeys("selenium测试");
        su.click();
        Thread.sleep(3000);
        System.out.println("getTitle--->"+webdriver.getTitle());
    }
}

问题:上面WebElement su及WebElement kw是怎么被实例化的?

PageFactory.initElements(webdriver, this)

这句代码,初始化Element,跑进去看看

public static void initElements(WebDriver driver, Object page) {
    final WebDriver driverRef = driver;
    initElements(new DefaultElementLocatorFactory(driverRef), page);
  }

并没有看到赋值继续走

public static void initElements(ElementLocatorFactory factory, Object page) {
    final ElementLocatorFactory factoryRef = factory;
    initElements(new DefaultFieldDecorator(factoryRef), page);
  }

继续

public static void initElements(FieldDecorator decorator, Object page) {
    Class<?> proxyIn = page.getClass(); // 取得LoginPage.class 
    while (proxyIn != Object.class) {   
      proxyFields(decorator, page, proxyIn);  //跟进去看看
      proxyIn = proxyIn.getSuperclass();
    }
  }

看到下面的代码有没有熟悉的感觉,没错就是根据反射取得该类的Filed: Field[] fields = proxyIn.getDeclaredFields();
在对其进行赋值操作:
field.setAccessible(true);
field.set(page, value);

private static void proxyFields(FieldDecorator decorator, Object page, Class<?> proxyIn) {
    Field[] fields = proxyIn.getDeclaredFields();
    for (Field field : fields) {
      Object value = decorator.decorate(page.getClass().getClassLoader(), field);
      if (value != null) {
        try {
          field.setAccessible(true);
          field.set(page, value);
        } catch (IllegalAccessException e) {
          throw new RuntimeException(e);
        }
      }
    }
  }

以上就是PageFactory如何对WebElenment赋值操作的,但是问题又来了值从哪儿来?见下回分解

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值