简体   繁体   中英

How to throw custom exception instead of NoSuchElementException in selenium

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

You can also use below approach:

try{
    driver.findElement(By.xpath(xpath)).isDisplayed()
 }
catch(Exception ex){
    throw new Exception("element not found");
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM