【发布时间】:2019-08-02 07:35:13
【问题描述】:
我正在尝试从链接元素等于字符串的列表元素中单击一个元素。我需要验证如果它们不相等会抛出错误。
当我比较的字符串与使用 if 语句的元素匹配时,它可以工作。一旦我在 else 语句中添加了一个条件,我就会得到一个错误。它以某种方式列出了整个元素
public void clickFromList(By element, String item) throws Exception{
try {
List<WebElement> linkElements = driver.findElements(element);
for (WebElement webElement : linkElements) {
String eleText = webElement.getText();
if(eleText.matches(item)) {
System.out.println("Selected: " + eleText);
webElement.click();
System.out.println("Clicked: " + eleText);
break;
}else {
Assert.assertFalse(true, "Error");
}
}
} catch (NoSuchElementException e) {
Assert.fail("Can't find the element in the page. The element is: " +element);
}
}
例外:
java.lang.AssertionError: Error expected [false] but found [true]
【问题讨论】:
-
如果你想让你的方法抛出错误,抛出异常,不要使用断言。
-
嗨@Stultuske,我试过了。它使我的 if 语句失败,因为它只捕获了第一个元素。是否需要将元素添加到arraylist?
-
我不明白你在说什么。一旦您的迭代遇到一个不相等的值,它就会抛出该错误,最好只保留您在迭代期间更新的标志(布尔值),并在迭代完成后检查该值。
-
嗨,我添加了一个布尔值,它起作用了。谢谢你的帮助。 :)
标签: java selenium cucumber cucumber-java