2

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?

Jose Da Silva Gomes
  • 3,814
  • 3
  • 24
  • 34

2 Answers2

2

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.

Grasshopper
  • 8,908
  • 2
  • 17
  • 32
  • Thanks, i had a similar thought. Having said that, the reason of creating pageobject interface is to implement as many pageobjects as possible. I want to access webelement without specifying classname. Could you please suggest some workaround? – Bhanu Bhaskar Apr 06 '18 at 20:25
0

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.

Arnon Axelrod
  • 1,444
  • 2
  • 13
  • 21
  • In second para, do you mean static and final?, If yes, then this is also correct, but the first one is what I was actually looking for. – Bhanu Bhaskar Apr 06 '18 at 20:31