[英]Selenium + Java = FindElements (list) and check if some of them contains a specific text
我的問題:
假設我有一個頁面顯示我購買的產品。 在此頁面中,我需要驗證添加的這些產品之一是否包含與我在上一步中獲得並放入 var ( String firstProductName
) 中的名稱相同的名稱。
所以我注意到 cssLocator .name
是所有這些產品名稱的定位器。 如果我只購買了一個產品,我會通過這個定位器找到它並使用getText()
來驗證是否包含與我存儲在 var firstProductName
中的名稱相同的名稱。
問題是:有時我只有一種產品,有時我有不止一種。
我需要:
.name
定位器查找所有元素。getText()
方法找到的文本是否包含我的字符串firstProductName
我怎么做?
就像是:
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
}
您可以將所有這些都包裝在一個函數中,如下所示。
/**
* 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;
}
然后在你的測試代碼中你會做類似的事情
assertTrue(foundProduct("some product name"));
但我不知道你是否在使用 TestNG 等。基本上,如果返回true
則測試通過,如果返回false
則測試失敗。
對於 Java 8 及更高版本,請嘗試此解決方案
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.