Recovery Scenarios in Selenium WebDriver
Recovery scenarios allow your test to handle unexpected failures gracefully — catch an error and attempt a recovery action instead of letting the test terminate abruptly.
Basic Try-Catch:
@Test
public void recoveryTest() {
try {
driver.get("www.xyz.com");
} catch (Exception e) {
System.out.println(e.getMessage());
// Recovery action: navigate to alternate URL or log and continue
}
}
Recover from NoSuchElementException:
@Test
public void elementRecovery() {
try {
driver.findElement(By.id("loginBtn")).click();
} catch (NoSuchElementException e) {
System.out.println("Login button not found, trying alternate locator");
// Recovery: try alternate locator
driver.findElement(By.cssSelector("button[type=''submit'']")).click();
}
}
Recover from StaleElementReferenceException:
@Test
public void staleElementRecovery() {
int retries = 3;
while (retries > 0) {
try {
driver.findElement(By.id("dynamicElement")).click();
break; // Success — exit loop
} catch (StaleElementReferenceException e) {
retries--;
System.out.println("Stale element, retrying... " + retries + " retries left");
Thread.sleep(500);
}
}
}
Recovery with screenshot on failure:
@Test
public void testWithRecovery() {
try {
driver.get("https://example.com");
driver.findElement(By.id("nonExistent")).click();
} catch (NoSuchElementException e) {
// Capture screenshot for evidence
TakesScreenshot ts = (TakesScreenshot) driver;
File screenshot = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("recovery_screenshot.png"));
System.out.println("Recovery: element not found. Screenshot captured.");
// Optionally: navigate to known state and retry
driver.navigate().refresh();
}
}
Recovery in @AfterMethod (TestNG):
@AfterMethod
public void recoverIfNeeded(ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
System.out.println("Test failed — performing cleanup recovery");
try {
driver.manage().deleteAllCookies();
driver.navigate().to("https://example.com");
} catch (Exception e) {
System.out.println("Recovery also failed: " + e.getMessage());
}
}
}
Common recovery exceptions to handle:
| Exception | Recovery Action |
|---|---|
NoSuchElementException | Try alternate locator or wait |
StaleElementReferenceException | Re-find element, retry |
TimeoutException | Increase wait or skip assertion |
ElementNotInteractableException | Scroll to element, JS click |
WebDriverException | Restart driver, refresh page |
Key answer: Use Try-Catch blocks within Selenium WebDriver Java tests for recovery scenarios. Catch the exception, log it, take a screenshot if needed, and attempt a recovery action.
