1. Implicit Wait
Implicit wait is used to set a default waiting time (say 30 seconds) throughout the WebDriver instance life cycle. It waits for a specified amount of time when trying to find an element or elements if they are not available immediately. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
2. Explicit Wait
Explicit wait is used to halt the execution until a particular condition is met or the maximum time has elapsed. Unlike implicit waits, explicit waits are applied for a particular instance only.
WebDriverWait wait = new WebDriverWait(driver, 20); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("someid")));
3. Fluent Wait
Fluent wait allows more flexible wait by defining the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition (polling rate). Users can also configure it to ignore specific types of exceptions while waiting, such as NoSuchElementException when searching for an element on the page.
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(Duration.ofSeconds(30)) .pollingEvery(Duration.ofSeconds(5)) .ignoring(NoSuchElementException.class); WebElement foo = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) {
return driver.findElement(By.id(“foo”));
}
});
4. Thread.sleep()
Although not a part of Selenium’s wait strategies, Thread.sleep() is a Java method that can be used to pause the execution of the program for a fixed duration. It is generally recommended to avoid using Thread.sleep() in your tests except for a very few specific cases because it forces a hard wait and can make test execution unnecessarily long.
Thread.sleep(1000); // Sleep for 1 second
Differences and When to Use:
- Implicit Wait: Use when you need a default wait time for all elements in the script, reducing the amount of repetitive code.
- Explicit Wait: Ideal for waiting for specific conditions on certain elements, providing flexibility and precision.
- Fluent Wait: Offers the most flexible waiting option, allowing customization of the polling interval and the ability to ignore specific exceptions.
- Thread.sleep(): Should be avoided in test scripts due to its inflexible nature and impact on test execution time. It may be used in very rare cases where a fixed pause is absolutely necessary.