Common Exceptions In Selenium WebDriver

 



Exceptions in Selenium WebDriver are errors that occur while executing test scripts. 


Some common exceptions in Selenium WebDriver include:



1. NoSuchElementException: This exception is thrown when an element is not found on the web page. This can occur when a test script is trying to interact with an element that does not exist or is not visible to the user.




2. StaleElementReferenceException: This exception is thrown when an element is no longer present in the DOM (Document Object Model) after a page refresh or navigation. 

This can occur when a test script is trying to interact with an element that was previously found but is no longer available.


try {
    WebElement element = driver.findElement(By.id("elementId"));
    element.click();
    driver.navigate().refresh();
    element.click();
} catch (StaleElementReferenceException e) {
    System.out.println("Element is stale: " + e.getMessage());
}
 



3. TimeoutException: This exception is thrown when a test script is trying to find an element and it takes more time than the specified time.



4. InvalidSelectorException: This exception is thrown when an invalid selector is used to locate an element.



5. WebDriverException: This is a general exception that is thrown when a WebDriver method fails.



To handle these exceptions, you can use try-catch blocks in your test scripts. For example:



try {
 
    //code that could throw an exception
 
    WebElement element = driver.findElement(By.id("elementId"));
 
    element.click();
 
} catch (NoSuchElementException e) {
 
    //code to handle the exception
 
    System.out.println("Element not found: " + e.getMessage());
 
}



In this example, the code that could throw a NoSuchElementException is placed inside the try block, and the code to handle the exception is placed inside the catch block. You can also use multiple catch blocks to handle different types of exceptions. 

Additionally, you can use the Assert.assertTrue() method to check the conditions that could cause an exception and fail the test case if the condition is not met.

Post a Comment

Post a Comment (0)

Previous Post Next Post