Explicit wait (WebDriverWait) in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import static org.junit.jupiter.api.Assertions.assertEquals; public class ExplicitWaitTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com/login"); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement loginButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("loginBtn"))); loginButton.click(); wait.until(ExpectedConditions.urlToBe("https://example.com/dashboard")); String currentUrl = driver.getCurrentUrl(); assertEquals("https://example.com/dashboard", currentUrl, "URL after login should be dashboard"); System.out.println("Test Passed: Login button clicked and dashboard loaded."); } catch (Exception e) { System.out.println("Test Failed: " + e.getMessage()); } finally { driver.quit(); } } }
This test script uses Selenium WebDriver with Java to automate the manual test case.
First, it opens the Chrome browser and navigates to the login page URL.
Then, it creates a WebDriverWait object with a 10-second timeout to wait explicitly for the login button to become clickable. This avoids using Thread.sleep which is unreliable.
Once the login button is clickable, the script clicks it.
Next, it waits until the URL changes to the dashboard URL to confirm navigation.
Finally, it asserts that the current URL is exactly the dashboard URL, ensuring the login action succeeded.
The try-catch block handles any exceptions gracefully, and the finally block closes the browser to clean up.
Now add data-driven testing with 3 different login button IDs to verify the wait works for each.
Practice
WebDriverWait in Selenium tests?Solution
Step 1: Understand the role of waits in Selenium
Waits help tests handle dynamic page content by pausing until elements are ready.Step 2: Identify what
WebDriverWaitdoesWebDriverWaitexplicitly waits for a condition like element visibility or clickability before proceeding.Final Answer:
To pause the test until a specific condition is met or timeout occurs -> Option CQuick Check:
Explicit wait = pause until condition met [OK]
- Confusing explicit wait with implicit wait
- Thinking it speeds up tests by skipping steps
- Using it to retry tests automatically
WebDriverWait object with a 10-second timeout in Java?Solution
Step 1: Recall the constructor for WebDriverWait in Selenium 4+
It requires the WebDriver instance and a Duration object for timeout.Step 2: Match the correct syntax
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); usesDuration.ofSeconds(10)correctly with the driver as first argument.Final Answer:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); -> Option DQuick Check:
Use Duration for timeout in WebDriverWait [OK]
- Passing timeout as int instead of Duration
- Swapping driver and timeout arguments
- Using deprecated constructors
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement button = wait.until(ExpectedConditions.elementToBeClickable(By.id("submitBtn")));
button.click();Solution
Step 1: Understand the wait condition and timeout
The wait will pause up to 10 seconds for the button to become clickable.Step 2: Analyze the element state after 5 seconds
The button becomes clickable after 5 seconds, so wait.until returns the element successfully.Final Answer:
The test waits up to 10 seconds, finds the button when clickable, then clicks it -> Option AQuick Check:
Waits up to timeout, proceeds when condition met [OK]
- Assuming immediate failure if element not ready
- Thinking wait always waits full timeout
- Confusing stale element with clickable condition
WebDriverWait:WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));
Solution
Step 1: Check the WebDriverWait constructor usage
Since Selenium 4, the timeout must be a Duration object, not an int.Step 2: Confirm the correct way to specify timeout
UseDuration.ofSeconds(10)to specify 10 seconds timeout.Final Answer:
Timeout value should be wrapped in Duration.ofSeconds() -> Option BQuick Check:
Timeout must be Duration, not int [OK]
- Passing int instead of Duration causes compile error
- Ignoring import errors for ExpectedConditions
- Misunderstanding return type of wait.until()
WebDriverWait?Solution
Step 1: Use try-catch to handle timeout without failing test
Wrap the wait in try block and catchTimeoutExceptionto log and continue.Step 2: Use
CreateelementToBeClickablewith correct selector and timeoutWebDriverWaitwith 5 seconds timeout and wait for clickable condition.Step 3: Click the button if found, else log message
If wait succeeds, click the button; if timeout occurs, catch block logs message and test continues.Final Answer:
Code with try-catch around wait and logging on timeout -> Option AQuick Check:
Handle timeout with try-catch to continue test [OK]
- Not catching TimeoutException causing test failure
- Using visibility instead of clickable condition
- Logging message after wait without exception handling
Ready to prove it?
Pass the test and this pattern moves unknown
