Implicit wait 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 java.time.Duration; import static org.junit.jupiter.api.Assertions.assertTrue; public class ImplicitWaitTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { // Set implicit wait of 10 seconds driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); // Navigate to test page driver.get("https://example.com/dynamic_loading"); // Click button to load dynamic element WebElement loadButton = driver.findElement(By.id("loadButton")); loadButton.click(); // Find dynamic element by id WebElement dynamicElement = driver.findElement(By.id("dynamicElement")); // Assert dynamic element is displayed assertTrue(dynamicElement.isDisplayed(), "Dynamic element should be visible after loading"); System.out.println("Test Passed: Dynamic element is displayed."); } finally { driver.quit(); } } }
This code sets an implicit wait of 10 seconds right after creating the WebDriver. This means Selenium will wait up to 10 seconds when trying to find elements before throwing an error.
We open the test page, click the button that triggers loading the dynamic element, then try to find that element by its id. Because of the implicit wait, Selenium will keep trying until the element appears or the timeout expires.
We then assert that the element is displayed to confirm it loaded successfully. Finally, the browser closes.
This approach is simple and uses implicit wait correctly by setting it once. It uses stable locators and proper assertions to verify the test outcome.
Now add data-driven testing with 3 different buttons that load different dynamic elements