Selenium WebDriver

Synchronization in Selenium

Master synchronization concepts including implicit wait, explicit wait, and fluent wait to handle dynamic web elements effectively.

Understanding Synchronization

What is Synchronization?

Synchronization is a process of matching the speed of application under test and test tool to ensure proper execution flow. During test execution, some elements take longer to become visible while others appear quickly.

Why Do We Need Synchronization?

  • • Web pages load at different speeds
  • • Elements appear dynamically based on user actions
  • • Network latency affects element loading
  • • JavaScript execution can delay element availability

Types of Synchronization

1. Unconditional Synchronization (Static Wait)

⚠️ Thread.sleep()

Waits for a fixed amount of time regardless of element availability. Not recommended for production use.

Thread.sleep(5000); // Waits exactly 5 seconds

Disadvantages

  • • Always waits for full duration
  • • Slows down test execution
  • • Not dynamic or intelligent
  • • Can cause unnecessary delays

2. Conditional Synchronization (Dynamic Wait)

✅ Dynamic Wait Types

Intelligent waits that check conditions periodically and proceed as soon as the condition is met.

Implicit Wait
Global wait for all elements
Explicit Wait
Local wait with conditions
Fluent Wait
Customizable polling wait

Implicit Wait

Characteristics

  • • Also called Global Wait
  • • Applies to all findElement() methods
  • • Dynamic wait behavior
  • • Defined once in Base class
  • • Throws NoSuchElementException on timeout

Syntax

driver.manage().timeouts()
  .implicitlyWait(Duration.ofSeconds(30));

How It Works

1. Set once for entire driver session
2. Applies to every findElement() call
3. Waits up to specified time
4. Proceeds immediately when element found
5. Throws exception if timeout reached

Example Scenario

If set to 30 seconds but element appears in 2 seconds, it will proceed immediately, ignoring remaining 28 seconds.

Complete Example

package Tutorial17;

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;

public class Demo1 {
    public static void main(String[] args) {
        ChromeDriver driver = new ChromeDriver();
        driver.get("https://www.facebook.com/reg");

        // Set implicit wait
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));

        // All findElement calls will use implicit wait
        driver.findElement(By.name("firstname")).sendKeys("Ajay");
        driver.findElement(By.name("lastname")).sendKeys("Yadav");
    }
}

Explicit Wait

Characteristics

  • • Also called Local Wait
  • • Applied to specific elements
  • • Requires ExpectedConditions
  • • More flexible than Implicit Wait
  • • Throws TimeoutException on timeout

Common ExpectedConditions

• visibilityOf(element)
• elementToBeClickable()
• presenceOfElementLocated()
• alertIsPresent()
• frameToBeAvailable()

Basic Syntax

WebDriverWait wait = new WebDriverWait(
  driver, Duration.ofSeconds(30));

wait.until(ExpectedConditions
  .visibilityOf(element)).sendKeys("text");

Advanced Usage

wait.until(ExpectedConditions
  .elementToBeClickable(By.id("btn")))
  .click();

Complete Example

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));

// Wait for element to be visible and interact
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("lastname")))
    .sendKeys("Yadav");

// Wait for element to be clickable
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[text()='Login']")))
    .click();

// Wait for alert and accept
wait.until(ExpectedConditions.alertIsPresent()).accept();

Fluent Wait

Advanced Features

  • • Customizable polling frequency
  • • Exception ignoring capability
  • • Most flexible wait mechanism
  • • Supports custom conditions
  • • Local wait for specific elements

Key Methods

• withTimeout() - Maximum wait time
• pollingEvery() - Check frequency
• ignoring() - Ignore exceptions
• until() - Wait condition

Basic Syntax

FluentWait<WebDriver> wait =
  new FluentWait<WebDriver>(driver)
  .withTimeout(Duration.ofSeconds(30))
  .pollingEvery(Duration.ofSeconds(5))
  .ignoring(Exception.class);

Custom Function

WebElement element = wait.until(
  new Function<WebDriver, WebElement>() {
    public WebElement apply(WebDriver driver) {
      return driver.findElement(By.id("id"));
    }
  });

Polling Timeline Example

Scenario: 30-second timeout with 5-second polling
0s
5s
10s
15s
20s
25s
30s (Timeout)
Checks for element every 5 seconds until found or 30 seconds elapsed

Wait Types Comparison

FeatureImplicit WaitExplicit WaitFluent Wait
ScopeGlobal (All elements)Local (Specific element)Local (Specific element)
ConditionsElement presence onlyMultiple conditionsCustom conditions
PollingFixed (500ms)Fixed (500ms)Customizable
Exception HandlingNoSuchElementExceptionTimeoutExceptionConfigurable
Best Use CaseGeneral element waitingSpecific conditionsComplex scenarios

Knowledge Check

Knowledge Check

Question 1 of 5

What is the main purpose of synchronization in Selenium?

Key Points Summary

🎯 Best Practices

  • • Use Explicit Wait for specific conditions
  • • Set reasonable timeout values
  • • Avoid Thread.sleep() in production
  • • Combine different wait strategies wisely

⚡ Performance Tips

  • • Use shorter timeouts for fast elements
  • • Implement proper exception handling
  • • Choose appropriate polling intervals
  • • Monitor wait effectiveness in logs

🔄 When to Use Which Wait

  • • Implicit: General element loading
  • • Explicit: Specific conditions
  • • Fluent: Complex polling needs
  • • Thread.sleep: Only for debugging

🚨 Common Pitfalls

  • • Mixing implicit and explicit waits
  • • Using excessive timeout values
  • • Not handling timeout exceptions
  • • Overusing static waits

SDET Mastery

Master Test Automation

Home
CurriculumPracticeQ&ACheatsheet
🍵Buy me a Chai

Automation Testing Course

Comprehensive course covering Manual Testing, Java Programming, and Selenium WebDriver

🍵Buy me a Chai
Privacy Policy•GitHub
© 2024 Automation Testing Course. All rights reserved.