简体   繁体   中英

Passing variable to webelement defined with annotation in Selenium Java

I use annotations to declare webelement in selenium java. In most of the cases i have simple locator:

@FindBy(how = How.ID, using="login")
WebElement btnLogin;

public void clickLogin() {
        btnLogin.click()
    }

But then there are sometimes cases when I need to pass variable into xpath or any other locator. In this situation I do that without declaring webelement before but in the function instead:

 public void clickElement(String elementName) {
         driver.findElementByXpath("//android.widget.TextView[@text='" + elementName + "']")
    }

I dont like it because locators should be called before in one place and not mixed with functions for code visibility

I thought of doing something like this:

String elementXpathPrePart= "//android.widget.TextView[@text='";
String elementXpathPostPart = "']";

and then

public void clickElement(String elementName) {
             driver.findElementByXpath(elementXpathPrePart + elementName + elementXpathPostPart )
        }

Do you have any solution for this?

Well, this is a common issue in the Page object model when you are using the page factory. Solutions for this:

  1. Use constants,java file and keep all xpaths there are refer from there

    public class Constants{ public static final String myxpath="//input[@id='username'] } In-Page class:

    @FindBy(how = How.ID, using=Constants.myxpath) WebElement btnLogin;

OR

In code

public void clickElement(String elementName) {
             driver.findElementByXpath(By. xpath(Constants.myxpath ).click()
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM