3

Is it possible to handle dynamic elements in Page Object Model?

Example:

package pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class Home_Page {
    WebDriver driver;

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

    @FindBy(how=How.XPATH, using = "//input[@name = '%s']")
    public WebElement inputField;
}

I want to pass the name attribute value of input, from my test method.

package scripts;

@Test
public void test(){
        driver.get("url");
        Home_Page homepage = PageFactory.initElements(driver, Home_Page.class);
        homepage.inputField.sendKeys("xpathParameter", "sendKeysVal"); 
}
Kass
  • 31
  • 1
  • 3

2 Answers2

2

It's not possible to implement the way you want since there is no way to dynamically pass a value to annotation in Java - Java Annotations values provided in dynamic manner.

However, you can achieve the same replacing your|class field + annotation| with |method|:

package pages;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;

public class Home_Page {
    WebDriver driver;

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

    public WebElement inputField(String name) {
       return this.driver.findElement(String.format(By.xpath("//input[@name = '" + name + "']");
    }
}


package scripts;

    @Test
    public void test(){
        driver.get("http://play.krypton.infor.com");
        Home_Page homepage = PageFactory.initElements(driver, Home_Page.class);
        homepage.inputField("xpathParameter").sendKeys("sendKeysVal"); 
    }
Vladimir Efimov
  • 797
  • 5
  • 13
0

Something of this sort should be useful in case you want to find an element using findBy and provide a pagename dynamically.

import org.openqa.selenium.By;
public class CreateLocators {
    public static By buildByObject(String pageName, String fieldName) {
        try {
            Class<?> clas = Class.forName("pageobjects." + pageName);
            Object obj = clas.newInstance();
            return new Annotations(obj.getClass().getDeclaredField(fieldName)).buildBy();
        } catch (NoSuchFieldException e) {
            return null;
        }
    }
}

In StepDef, you should be doing like:

byElem = CreateLocators.buildByObject(pageName, desiredElementNameInPO);
        elem = driver.findElement(byElem);
        elem.click();
Das_Geek
  • 2,775
  • 7
  • 20
  • 26