简体   繁体   中英

Selenium page object pattern locator parameters

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?

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

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.

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