Tuesday, September 27, 2016

Selenium Exception Handling

Selenium Exception Handling

Exception Handling

When we are developing tests, we should ensure that the scripts can continue its execution even if the test fails. An unexpected exception would be thrown if the worst case scenarios are not handled properly.

If an exception occurs due to element not found or if the expected result doesn't match with actuals, we should catch that exception and end the test in a Logical way that the script itself terminating abruptly.

Syntax

The actual code should be placed in try block and the action after exception should be placed in catch block. Please Note 'finally' block would be no matter if the script had thrown exception or NOT.

try { //Perform Action } catch(ExceptionType1 exp1) { //Catch block 1 } catch(ExceptionType2 exp2) { //Catch block 2 } catch(ExceptionType3 exp3) { //Catch block 3 } finally { //The finally block always executes. }

Example

If an element not found(because of any good reason), we should ensure that we step out of the function smoothly. So always need to have try-catch block if we want to do the same.

public static WebElement lnk_percent_calc(WebDriver driver)throws Exception { try { element = driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")); return element; } catch (Exception e1) { // Add a message to your Log File to capture the error Logger.error("Link is not found."); // Take a screenshot which will be helpful for analysis. File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshot, new File("D:\\framework\\screenshots.jpg")); throw(e1); } }

No comments:

Post a Comment