Search code examples
javaappiumpageobjects

How can I pass a variable to the element found using Appium @FindBy


Is there a way to dynamically set the xpath or id used by Appium @FindBy() so I dont have to create a dozen individual WebElements?

I am using the Page Object Model to automate a mobile app. I use to just create a method that would find an element based on a string I would pass it but now I am trying to use annotations to get my elemetents.

Estinally I am hoping there is a way to basically do this

class Page{
    AppiumDriver driver;
    
    public Page(AppiumDriver driver){
        this.driver = driver
        PageFactory.initElements(new AppiumFieldDecorator(driver), this)
    }
    
    @iOSXCUITFindBy(xpath = "//*[@text='"+option+"']")
    @AndroindFindBy(xpath = "//*[@text='"+option+"']")
    private WebElement dynamicOption(option)


    public void selectOption(String option){
        dynamicOption(option).click()
    }
}
@Test
public void testAThing(){
    Page page = new Page(driver);
    page.selectOption("New");
}

I understand that the syntax probably doesn't make sense but this is the general idea of what I want to do

I used to do something like this but I want to know if there is a way with annotations

private WebElement dynamicOption(String option){
    return driver.findElement(By.xpath("//*[@text='"+option+"']"));
}

Solution

  • After over a month of no answer I am pretty sure that my WebElement function is the only way I can do what I want

    private WebElement dynamicElement(String locator) {
            if (driver.getClass() == AndroidDriver.class) {
                return driver.findElement(AppiumBy.xpath(
                            String.format("//android.widget.TextView[@text='%s']", locator)));
            } 
            else {
                return driver.findElement(AppiumBy.iOSClassChain(
                            String.format("**/XCUIElementTypeStaticText[`label == \"%s\"`]", locator)));
            }
        }