java: String.format with PageFactory



  • This is My String in non PageFactory framework, declared at the class level.

    private final String fruits= "//a/h4[text()='%s']";
    

    Which is used in same class in some method like this:

    public void clickFruitHeading(String string) {
            driver.click(By.xpath(String.format(fruits, string)));
            driver.click(By.xpath(String.format(fruits, "Apple")));
        }
    

    But when using PageFactory it is written like this:

    @FindBy(xpath = "//a/h4[text()='%s']")
    private static WebElement fruits;
    

    How to use String.format here?



  • There's no way to do it with PageFactory without re-implementing it. Locators to page object elements in @FindBy annotations cannot be updated at runtime. You probably would like to have something like

    fruits("Apple").click();
    

    However, the proxy created by PageFactory for fruits field accessor does not take any arguments. It just does something like:

    driver.findElement(By.xpath("//a/h4[text()='%s']");
    

    The closest thing that you can do is to refrain from using @FindBy for this particular element on a Web page, define a method:

    private WebElement fruits(String fruit) {
      By.xpath(String.format("//a/h4[text()='%s']", fruit));
    }
    

    and then call it:

    fruits("Apple").click();
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2