如何验证Selenium 2中不存在元素 [英] How do I verify that an element does not exist in Selenium 2

查看:169
本文介绍了如何验证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());
....

这篇关于如何验证Selenium 2中不存在元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆