断言 WebElement 不存在,使用 Selenium WebDriver 和 java

2022-09-01 01:25:14

在我编写的测试中,如果我想断言页面上存在WebElement,我可以做一个简单的操作:

driver.findElement(By.linkText("Test Search"));

如果它存在,这将通过,如果它不存在,它将爆炸。但现在我想断言链接不存在。我不清楚如何做到这一点,因为上面的代码不返回布尔值。

编辑这就是我想出自己的解决方案的方式,我想知道是否有更好的方法。

public static void assertLinkNotPresent (WebDriver driver, String text) throws Exception {
List<WebElement> bob = driver.findElements(By.linkText(text));
  if (bob.isEmpty() == false) {
    throw new Exception (text + " (Link is present)");
  }
}

答案 1

这样做更容易:

driver.findElements(By.linkText("myLinkText")).size() < 1

答案 2

我认为你可以抓住如果没有这样的元素就会被抛出:org.openqa.selenium.NoSuchElementExceptiondriver.findElement

import org.openqa.selenium.NoSuchElementException;

....

public static void assertLinkNotPresent(WebDriver driver, String text) {
    try {
        driver.findElement(By.linkText(text));
        fail("Link with text <" + text + "> is present");
    } catch (NoSuchElementException ex) { 
        /* do nothing, link is not present, assert is passed */ 
    }
}

推荐