java - 如何在 selenium 中抛出自定义异常而不是 NoSuchElementException

标签 java firefox xpath selenium-webdriver

当找不到元素的 xpath 时,我希望在 selenium 中抛出自定义错误消息 我创建了一个类

package NewPackage;

public class ExplicitAssertionError extends AssertionError {
    private static final long serialVersionUID = 1L;
    public ExplicitAssertionError (String msg) {
        super(msg);
    }
}

我写过这样的代码来测试一个页面

public class ResultPage extends WDBase {
    public void assertTravelNamePresent(final String busName) {
        final String xpath="//div[@class='company'][contains(.,'"+busName+"')]";
        if (!driver.findElement(By.xpath(xpath)).isDisplayed()) {
                throw new ExplicitAssertionError("invalid text found");
        }
    }
}

此处,当传递与页面的 xpath 不匹配的无效文本时,将抛出 NoSuchElementException 而不是错误消息。 在找不到元素的情况下,任何人都可以为我提供一个使用 assertTrue/False 使测试用例失败的解决方案 谢谢

最佳答案

使用findElements()方法检查长度:

if (driver.findElements(By.xpath(xpath)).size() == 0) {
    throw new ExplicitAssertionError("element not found");
}

关于java - 如何在 selenium 中抛出自定义异常而不是 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36481179/

相关文章:

javascript - Firefox 的 Math.round 或 Date 不同吗?

c# - 在 HtmlAgilityPack、Xpath 中使用谓词

java - Spring MVC @Controller 和配置文件

javascript - 对字符串的 promise - [object Object] 或 [object Promise]?

java - 在 libgdx 中暂停 TimeUtils

html - 文本缩进对 div 的第一个子 span 元素有影响吗?

javascript - 如何使用 XPath 或 CSS 选择可见元素?

用于爬行的 XPath 跟随 sibling 不返回 sibling

java - sonarlint 强制将最终类的常量声明为 protected

java - 如何让 Java 在 Linux 中使用串口?