4

I've recently started using Selenium2 with the Page Object Pattern in conjunction with Page Factory. I have the WebElements declared with @FindBy Annotations that are initialized by the PageFactory when the class is initialized. However I would like to use the @FindBy Annotation with a locators.properties file. Unfortunately I don't seem to be able to do this as the Annotation is restricted to only allowing Constant Expressions. This seems to be a limitation in Java Annotations in general but I'm just wondering if anybody has found a workaround for this. I would prefer to load the locators from an external source but then I would lose the benefits of using PageFactory.

public class LoginPage {

    protected WebDriver driver; 

    @FindBy(id = "username") 
    private WebElement usernameField; 

    @FindBy(id = "password") 
    private WebElement passwordField; 

    @FindBy(id = "button_login") 
    private WebElement loginButton; 

    public LoginPage(WebDriver driver) { 
            this.driver = driver; 
            PageFactory.initElements(driver, this); 
    } 

}

I would like to implement something similar to this but I can't because the Annotation will not allow this:

public class LoginPage {

    protected WebDriver driver; 

    Properties locators = new Properties(); 

    @FindBy(id = locators.getProperty("login.usernameField")) 
    private WebElement usernameField; 

    @FindBy(id = locators.getProperty("login.passwordField")) 
    private WebElement passwordField; 

    @FindBy(id = locators.getProperty("login.loginButton")) 
    private WebElement loginButton; 

    public LoginPage(WebDriver driver) { 
            this.driver = driver; 
            // Load the locators.properties File here 
            PageFactory.initElements(driver, this); 
    } 

}

user1785004
  • 41
  • 1
  • 2
  • I don't think it is possible. The values provided to any annotation is computed at compile time & not at run time. However, if your intention is to store locators in property file, then you could use By clause... Here is an example C# code: public By UserName() { return By.Id(locators.getProperty("login.usernameField")); } and later you could use Driver.FindElement(UserName()).SendKeys("").. – Pani Kumar Oct 31 '12 at 08:45
  • check this out, you may get some idea http://stackoverflow.com/questions/3981498/selenium-page-object-reuse – Kavan May 07 '15 at 18:37

2 Answers2

0

You can't at the moment.

You could always write a way to do it and offer it up as a patch that can be applied back into the Selenium codebase :)

Ardesco
  • 7,281
  • 26
  • 49
0

it is possible and this link is indeed helpful Selenium Page Object Reuse‌​se

I have managed to read locators from config, please take a look Selenium Page Object. How to read @FindBy locator from external source?

Community
  • 1
  • 1
ludenus
  • 1,161
  • 17
  • 30