Selenium WebDriver
Advanced Selenium Concepts & Exception Handling
Deep dive into synchronization, flaky scenarios, exception handling, and advanced Selenium concepts for robust test automation.
Synchronization in Detail
What is Synchronization?
Synchronization is the process of matching the speed of the application under test and the test tool to maintain proper test execution flow. Different elements load at different speeds, requiring proper timing strategies.
Why Synchronization?
- • Elements load at different speeds
- • Network latency variations
- • JavaScript execution delays
- • Dynamic content loading
- • Server response variations
Types of Synchronization
- • Unconditional (Static Wait)
- • Conditional (Dynamic Wait)
- • - Implicit Wait
- • - Explicit Wait
- • - Fluent Wait
Wait Strategies Detailed Comparison
Implicit Wait vs Explicit Wait
Aspect | Implicit Wait | Explicit Wait |
---|---|---|
Scope | All elements (Global) | Single element (Local) |
Expected Conditions | Not required | Required |
Exception | NoSuchElementException | TimeoutException |
Interface | Timeouts interface | WebDriverWait class |
Explicit Wait vs Fluent Wait
Similarities
- • Both are dynamic waits
- • Both apply to single elements
- • Both require ExpectedConditions
- • Both work with findElement/findElements
Key Differences
- • Fluent Wait: Custom polling frequency
- • Fluent Wait: Exception ignoring capability
- • Explicit Wait: Fixed polling (500ms)
- • Fluent Wait: FluentWait class
Flaky Scenarios in Selenium
What are Flaky Tests?
Flaky scenarios occur when the same test case sometimes passes and sometimes fails during execution, creating unreliable test results and reducing confidence in the test suite.
Common Causes
- • Timing and synchronization issues
- • Network latency variations
- • Dynamic content loading
- • Race conditions
- • Environment dependencies
- • Asynchronous operations
Solutions
- • Implement proper wait strategies
- • Use Explicit/Fluent waits
- • Add appropriate ExpectedConditions
- • Stabilize test environment
- • Handle dynamic elements properly
- • Implement retry mechanisms
Flaky Test Resolution Strategy
// Instead of direct element interaction
driver.findElement(By.id("submit")).click(); // Flaky
// Use explicit wait with expected conditions
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(
ExpectedConditions.elementToBeClickable(By.id("submit"))
);
element.click(); // Stable
driver.findElement(By.id("submit")).click(); // Flaky
// Use explicit wait with expected conditions
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(
ExpectedConditions.elementToBeClickable(By.id("submit"))
);
element.click(); // Stable
Selenium Exceptions & Handling
Common Selenium Exceptions
Understanding and properly handling exceptions is crucial for creating robust and maintainable test automation scripts.
WebDriverException
Cause: WebDriver library not found in pom.xml or .m2 repository
Solution: Check WebDriver dependency in pom.xml
SessionNotCreatedException
Cause: Browser and driver version mismatch
Solution: Update driver to match browser version
NoSuchElementException
Cause: Element not found in HTML DOM
Solution: Verify locator and add proper waits
TimeoutException
Cause: Element not found within specified wait time
Solution: Increase timeout or fix locator
StaleElementReferenceException
Cause: Element existed before but not in current DOM
Solution: Re-locate element or refresh page
ElementClickInterceptedException
Cause: Element is hidden or overlapped
Solution: Wait for element visibility or scroll
NoSuchWindowException
Cause: Trying to switch to non-existent window
Solution: Verify window exists before switching
NoAlertPresentException
Cause: Alert popup not present or already closed
Solution: Wait for alert presence before handling
Exception Handling Best Practices
try {
// Selenium operations
WebElement element = driver.findElement(By.id("submit"));
element.click();
} catch (StaleElementReferenceException e) {
// Re-locate element
WebElement element = driver.findElement(By.id("submit"));
element.click();
} catch (TimeoutException e) {
System.out.println("Element not found within timeout");
throw e;
} catch (NoSuchElementException e) {
System.out.println("Element not found: " + e.getMessage());
return false;
}
// Selenium operations
WebElement element = driver.findElement(By.id("submit"));
element.click();
} catch (StaleElementReferenceException e) {
// Re-locate element
WebElement element = driver.findElement(By.id("submit"));
element.click();
} catch (TimeoutException e) {
System.out.println("Element not found within timeout");
throw e;
} catch (NoSuchElementException e) {
System.out.println("Element not found: " + e.getMessage());
return false;
}
Advanced Screenshot Techniques
Screenshot Strategies
Regular Screenshot
- • TakesScreenshot interface
- • getScreenshotAs(OutputType.FILE)
- • FileUtils.copyFile() method
- • Captures visible viewport only
Full Page Screenshot
- • AShot library dependency
- • shootingStrategy() method
- • viewPortPasting() for scrolling
- • ImageIO.write() for saving
Full Page Screenshot Implementation
// Step 1: Create AShot object
AShot ashot = new AShot();
// Step 2: Set shooting strategy with scroll timing
ashot.shootingStrategy(ShootingStrategies.viewPortPasting(1000));
// Step 3: Take screenshot and get BufferedImage
BufferedImage source = ashot.takeScreenshot(driver).getImage();
// Step 4: Define destination file
File destination = new File("fullpage-screenshot.png");
// Step 5: Save using ImageIO
ImageIO.write(source, "PNG", destination);
AShot ashot = new AShot();
// Step 2: Set shooting strategy with scroll timing
ashot.shootingStrategy(ShootingStrategies.viewPortPasting(1000));
// Step 3: Take screenshot and get BufferedImage
BufferedImage source = ashot.takeScreenshot(driver).getImage();
// Step 4: Define destination file
File destination = new File("fullpage-screenshot.png");
// Step 5: Save using ImageIO
ImageIO.write(source, "PNG", destination);
Knowledge Check
Knowledge Check
Question 1 of 5
What is a flaky scenario in Selenium?
Advanced Concepts Summary
🎯 Synchronization Mastery
- • Use Explicit Wait for specific conditions
- • Fluent Wait for complex polling scenarios
- • Implicit Wait as baseline for all elements
- • Avoid mixing different wait strategies
⚡ Flaky Test Prevention
- • Implement proper wait strategies
- • Use ExpectedConditions appropriately
- • Handle dynamic content properly
- • Stabilize test environment
🔧 Exception Handling
- • Implement try-catch blocks strategically
- • Handle StaleElementReference by re-locating
- • Use appropriate recovery mechanisms
- • Log exceptions with meaningful messages
🚨 Best Practices
- • Keep browser and driver versions in sync
- • Use framework-level wait utilities
- • Implement proper screenshot strategies
- • Create reusable exception handling methods