1

Recently started playing around the Selenium page object pattern. And I understand the concept of the Selenium page object pattern and the PageFactroy. But what baffles me is the lack of flexibility it provides. For example how the page object pattern provide support for a simple locator parameter? How dynamic locators can be handled with the Selenium Page Object pattern?

To understand the question better please take the following scenario.

I have my login page.

public class LoginPage {
  private final WebDriver driver;

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

   By usernameLocator = By.id("username");
   By passwordLocator = By.id("passwd");
   By loginButtonLocator = By.id("login");

   public HomePage loginAs(String username, String password) {
      driver.findElement(usernameLocator).sendKeys(username);
      driver.findElement(passwordLocator).sendKeys(password);
      driver.findElement(loginButtonLocator).submit();
      return new HomePage(driver);
   }

}

And I have my Home page.

public class HomePage {

    private final WebDriver driver;

    By usernameLocator = By.xpath("//span[contains(text(),'Welcome <LoggedInUserName>')]");

    public HomePage(WebDriver driver) {
       this.driver = driver;
    }

    public HomePage checkLoggedInUser(String username) {
        // I want to parameterize the usernameLocator with the logged in username
        driver.findElement(usernameLocator);
        return this;
    }

}

In the Home page I want to check the span tag which contains the text "Welcome User1". User name can be changed according to the logged in user. And i want to parameterize the usernameLocator in the home page with the logged in username.

Ho can I parameterize the By locator and pass parameter values at the run time?

1 Answer 1

2

You can do this using method pass message as argument which return By object like below:

public By usernameLocator(String message) {
    return By.xpath(String.format("//span[contains(text(),'%s')]", message));
}

Call above method where required in Page file.

Thanks, Sadik

Sign up to request clarification or add additional context in comments.

2 Comments

But this is not the page object pattern? Is this the standard way of passing locator params for the object locator in Page object model?
This is same like you are defining locators in variable. If you want to pass value in object then you should use define locator in method in same class like above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.