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

Tru*_*lue 40 java assertion selenium-webdriver

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

driver.findElement(By.linkText("Test Search"));
Run Code Online (Sandbox Code Playgroud)

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

编辑这就是我提出自己修复的方法,我想知道是否还有更好的方法.

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)");
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 37

这样做更容易:

driver.findElements(By.linkText("myLinkText")).size() < 1
Run Code Online (Sandbox Code Playgroud)

  • 到目前为止,这是避免findElement抛出异常的更好答案. (3认同)
  • 好的解决方案。但是,这会尝试“超时”秒来查找元素。因此,您可能需要设置(然后重置)驱动程序超时。也许在一种方法中。 (2认同)

Ser*_*rov 12

如果没有这样的元素org.openqa.selenium.NoSuchElementException,我认为你可以抓住它会被抛出driver.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 */ 
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然这有效,但我认为它并不理想.如果将webdriver配置为隐式等待,则测试将变得非常慢. (3认同)
  • 这是非常不推荐的,它会减慢你的测试速度并且可能是难以发现的错误的来源: - 如果元素不存在(最常见),你的测试将每次等待隐式等待 - 如果元素是但它正在消失,隐式等待将不会被使用,你的测试将立即失败,这是一个误报. (2认同)

And*_*dre 9

不确定你指的是哪个版本的selenium,但selenium*中的一些命令现在可以这样做:http: //release.seleniumhq.org/selenium-core/0.8.0/reference.html

  • assertNotSomethingSelected
  • assertTextNotPresent

等等..


Fab*_*ney 6

有一个名为ExpectedConditions:

  By loc = ...
  Boolean notPresent = ExpectedConditions.not(ExpectedConditions.presenceOfElementLocated(loc)).apply(getDriver());
  Assert.assertTrue(notPresent);
Run Code Online (Sandbox Code Playgroud)