1

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?

2

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();
0

The PageFactory code isn't working because fruits isn't a WebElement to be found on the page as is, which is what that scheme is used for. Instead, it is a string substitution template and should be kept as just a "private final String".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.