Home > Blockchain >  How to parameterize the locators?
How to parameterize the locators?

Time:04-20

I am trying store all values required for locators in Property File:

This is Property File:

url=https://www.google.com
value=search   

This is my object repository class:

public class pageobjects extends helperclass{
public WebDriver driver;

By search  = By.xpath("//input[@aria-label='search12()']") //I am trying to insert helpclass method here.

public class pageobjects(Webdriver driver){ //creating constructor
  
 this.driver=driver; }

 public WebElement search(){
return driver.findElement(search);
}
}

Here I don't want to hardcode "Search" in my object repository file and in my testcase file so I trying to store in a Property File. I know that by using "load ()" and "getProperty()", I can read/load Property File.

This is my helper class to consists of methods to store particular String value from Property file:

public helperclass { 
public properties prop;


static String search12() { 
prop=new Properties();
FileInputStream fis = new FileInputStream(path of property file);
return prop.getProperty("value");
}

}

Error: The String //input[@aria-label='search12()'] is not valid Xpath expression.

CodePudding user response:

Why don't you try this - By.xpath("//input[@aria-label=" search12() "]")

CodePudding user response:

Your code:

public class pageobjects extends helperclass{
 By search  = By.xpath("//input[@aria-label='search12()']"); 
}

It is not possible to parameterize the elements once it was defined with By or WebElement. You need to parameterize before that.

Here search is not a String to replace with dynamic value. It is a locator and you cannot modify the locator value once it is defined.

You need to write a customized method to handle dynamic xPaths like below,

public class pageobjects extends helperclass {
    public WebDriver driver;

    String search = "//input[@aria-label='?12()']";

    public class pageobjects(
    Webdriver driver){        
     this.driver=driver; 
     }

        // Read property file and get the field value.
        getDynamicElement(search, valueFromPropertFile);

        public static WebElement getDynamicElement(String search, String value) {
            WebElement element = driver.findElement(By.xpath(search.replace("?", value)));
            return element;
        }
    }
  • Related