Home > OS >  How do I make an xpath with a variable for a selenide test
How do I make an xpath with a variable for a selenide test

Time:08-29

I want to write a testmethod which I can give a parameter which will define which element to test.

Something like;

public void addImage(String imageNr){
     $(By.xpath("(//input[@name='image'])['"   imageNr   "']"));
}

To get i.e. (//input[@name='image'])[2] or (//input[@name='image'])[3]

How would I go about that?

CodePudding user response:

within Selenide you have something called the ElementsCollection. More information can be found on this page: https://selenide.gitbooks.io/user-guide/content/en/selenide-api/elements-collection.html

What you can do is transform the SelenideElement to an ElementsCollection by using double dollar signs:

For example:

  • This .get requires an Integer type. It will give you first all elements and you can take the second element from the returned list.

$$(By.xpath("(//input[@name='image'])).get(pageNr)

You will still need to do an action after getting this. for Example .click();

Good luck with it.

CodePudding user response:

You can format the XPath String expression with the use of String.format, as following:

public void addImage(String imageNr){
    String xpath = "(//input[@name='image'])[{0}]";
    xpath = String.format(xpath,imageNr);
     $(By.xpath(xpath));
}
  • Related