简体   繁体   English

可以在与Selenium的接口中使用@findby批注

[英]Can @findby annotation be used in an interface with Selenium

Lets see below code: 让我们看下面的代码:

public interface HomePageObjects {

    @FindBy(xpath = "//*[@class='_2zrpKA']")
    WebElement UsernameField ;

    @FindBy(xpath = "//*[@class='_2zrpKA _3v41xv']")
    WebElement PswdField ;

}

public class HomePageTests implements HomePageObjects {

    WebDriver Driver;

    @BeforeClass
    public void initpage() {
        Driver = LaunchBrowser.Driver;
        PageFactory.initElements(Driver, this); 
        System.out.println(UsernameField + " " + Driver);
    }

}

This code compiles fine, but it is not able to initialize webelements, does any one has an explanation? 这段代码可以很好地编译,但是无法初始化Webelements,有人解释吗?

The source code for the PageFactory class , check the initElements method. PageFactory类的源代码,检查initElements方法。

public static void initElements(FieldDecorator decorator, Object page) {
    Class<?> proxyIn = page.getClass();
    while (proxyIn != Object.class) {
      proxyFields(decorator, page, proxyIn);
      proxyIn = proxyIn.getSuperclass();
    }
  }

The proxyIn.getSuperclass() returns the superclass of the pageobject ignoring the interface. proxyIn.getSuperclass()返回忽略接口的页面对象的超类。 So in your case it goes from HomePageTests.class to Object.class . 因此,在您的情况下,它从HomePageTests.classObject.class Thus the webelements in the interface will remain uninitialized. 因此,界面中的网络元素将保持未初始化状态。 You can look at using an abstract class instead which is a better idea for storing state. 您可以考虑使用抽象类代替,这是一种更好的状态存储方法。

In Java, fields that are declared as members of an interface are implicitly static and final . 在Java中,声明为接口成员的字段隐式为staticfinal Therefore, these members are not part of your object instance and therefore PageFactory.initElements doesn't initialize them. 因此,这些成员不属于您的对象实例,因此PageFactory.initElements不会初始化它们。

The same should happen also without using an interface - all @findBy annotations on static members will be ignored. 不使用接口也应该发生相同的情况-静态成员上的所有@findBy注释都将被忽略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM