Home > Software design >  How to solve Selenium Java Page Object problem with List<Webelement>
How to solve Selenium Java Page Object problem with List<Webelement>

Time:12-22

When we create Page(Class) for some WebElement(driver.findElements(By.xpath("//h4[@class='card-title']")) and this element is a part of a List do we change only that part im main testcase(after creating method for it) and the remaining is the same or not? example:

List<WebElement> products =driver.findElements(By.xpath("//h4[@class='card-title']"));
        for(int i=0;i<products.size();i  )
        {
            String name=products.get(i).getText();
            if(name.contains("Samsung"))
            {
                driver.findElements(By.xpath("//div[@class='card-footer']/button")).get(i).click();
                break;
            }   
        }

I am not sure about that and that's the reason for question

CodePudding user response:

With the given limited data in the question, it is pretty unclear but as far as my understanding goes it not the same piece of code. We should segregate the page classes and test cases(@test).

CodePudding user response:

When you create a Page class for a WebElement or a list of WebElements, you can encapsulate the code for interacting with that element or list of elements into a separate method in the Page class. This can make your test code more organized and easier to read and maintain.

In the example you provided, you could create a Page class with a method that takes a product name as an input, and then searches the list of products for a product with the given name and clicks the associated button. Here's an example of how this method could look:

public void clickButtonForProduct(String productName) {
  List<WebElement> products = driver.findElements(By.xpath("//h4[@class='card-title']"));
  for (int i = 0; i < products.size(); i  ) {
    String name = products.get(i).getText();
    if (name.contains(productName)) {
      driver.findElements(By.xpath("//div[@class='card-footer']/button")).get(i).click();
      break;
    }
  }
}

Then, in your test case, you can call this method and pass in the product name you want to search for:

page.clickButtonForProduct("Samsung");

This way, you only need to change the product name in your test case, and the rest of the code for searching the list of products and clicking the button remains the same.

  • Related