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?
The source code for the PageFactory class , check the initElements
method.
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. So in your case it goes from HomePageTests.class
to Object.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
. Therefore, these members are not part of your object instance and therefore PageFactory.initElements
doesn't initialize them.
The same should happen also without using an interface - all @findBy
annotations on static members will be ignored.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.