当找不到元素的 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/