如何验证Selenium 2中不存在元素
在Selenium 2中,我要确保驱动程序已加载的页面上的元素不存在.我在这里包括了我的幼稚实现.
In Selenium 2 I want to ensure that an element on the page that the driver has loaded does not exist. I'm including my naive implementation here.
WebElement deleteLink = null;
try {
deleteLink = driver.findElement(By.className("commentEdit"));
} catch (NoSuchElementException e) {
}
assertTrue(deleteLink != null);
有没有一种更优雅的方法可以从根本上验证断言是否引发了NoSuchElementException?
Is there a more elegant way that basically verifies to assert that NoSuchElementException was thrown?
如果您正在使用junit进行测试,而这只是您要进行的测试,则可以使测试使用来期待异常
If you are testing using junit and that is the only thing you are testing you could make the test expect an exception using
@Test (expected=NoSuchElementException.class)
public void someTest() {
driver.findElement(By.className("commentEdit"));
}
或者您可以使用findElements
方法返回元素列表,或者如果找不到元素列表则返回空列表(不抛出NoSuchElementException
):
Or you could use the findElements
method that returns an list of elements or an empty list if none are found (does not throw NoSuchElementException
):
...
List<WebElement> deleteLinks = driver.findElements(By.className("commentEdit"));
assertTrue(deleteLinks.isEmpty());
...
或
....
assertTrue(driver.findElements(By.className("commentEdit")).isEmpty());
....