我希望在找不到元素的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为我提供一个测试用例失败的解决方案 谢谢
答案 0 :(得分:3)
使用findElements()
方法检查长度:
if (driver.findElements(By.xpath(xpath)).size() == 0) {
throw new ExplicitAssertionError("element not found");
}
答案 1 :(得分:-1)
您也可以使用以下方法:
try{
driver.findElement(By.xpath(xpath)).isDisplayed()
}
catch(Exception ex){
throw new Exception("element not found");
}