如何抛出自定义的异常,而不是Selenium中的NoSuchElementException [英] How to throw custom exception instead of NoSuchElementException in selenium

查看:107
本文介绍了如何抛出自定义的异常,而不是Selenium中的NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  package NewPackage; 

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




$ b我写了这样的代码来测试一个页面

  public class ResultPage扩展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);





$ b这里当一个无效的文本是传递的是与页面的xpath不匹配的NoSuchElementException,而不是错误消息。
也可以给任何人提供一个解决方案失败的情况下使用assertTrue / False的情况下,找不到元素
谢谢

解决方案

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

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


I wish to throw a custom error message in selenium when an element's xpath is not found I have created a class

package NewPackage;

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

I have written code like this for testing a page

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");
        }
    }
}

Here when an invalid text is passed that is which is not matching with xpath of page NoSuchElementException is thrown instead of an error message. Also can anyone provide me a solution to fail a test case using assertTrue/False in cases where element is not found Thanks

解决方案

Use findElements() method and check the length:

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

这篇关于如何抛出自定义的异常,而不是Selenium中的NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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