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.