简体   繁体   中英

Selenium + Java = FindElements (list) and check if some of them contains a specific text

My question:

Let suppose I have a page with the products I bought. In this page I need to verify if one of these products added contains the same name that I got in a previous step and put into a var ( String firstProductName ).

So I notice the cssLocator .name is the locator for all these products' names. If I had only one product bought, I would just find it by this locator and use getText() to verify if contains the same name that I have stored in the var firstProductName .

The problem is: Sometimes I have only one product, sometimes I have more than one.

I need to:

  1. Access this page, find all elements with the .name locator.
  2. Then I need to check one by one seeing if through the getText() method the text found contains my string firstProductName
  3. If at least one have the name equals to this String, my test is ok. If not, the test fails.

How do I do that?

Something like:

List<WebElement> allProducts = select.findElements(By.cssSelector("{not quite clear what your selector is, but it includes "name"}"));
for (WebElement product: allProducts) {
    if(product.getText().equals(firstProductName)) 
        return; // or break or whatever
}

You could wrap this all up in a function as below.

/**
 * Determines if the supplied product name is found on the page
 * 
 * @param productName
 *            the product name to be searched for
 * @return true if the product name is found, false otherwise
 */
public boolean foundProduct(String productName)
{
    List<WebElement> products = driver.findElements(By.className("name"));
    for (WebElement product : products)
    {
        if (product.getText().trim().equals(productName))
            return true;
    }

    return false;
}

Then in your test code you would do something like

assertTrue(foundProduct("some product name"));

but I don't know if you are using TestNG, etc. Basically the test passes if true is returned or fails if false is returned.

For Java 8 and above try this solution

public boolean productsContainsProvidedProduct(String product) {

 List<WebElement> products = driver.findElements(By.xpath("your_xpath_to_list_of_elements"));  
 wait.until(ExpectedConditions.visibilityOfAllElements(products));
 return products.stream().anyMatch(e -> e.getText().trim().contains(product));
}

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