Reputation: 31
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:
.name
locator.getText()
method the text found contains my string firstProductName
How do I do that?
Upvotes: 1
Views: 4902
Reputation: 1868
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));
}
Upvotes: 0
Reputation: 25597
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.
Upvotes: 0
Reputation: 13970
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
}
Upvotes: 1