FluentWait with polling 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.FluentWait; import org.openqa.selenium.support.ui.Wait; import java.time.Duration; import java.util.NoSuchElementException; public class FluentWaitExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com/testpage"); // Click the load button driver.findElement(By.id("loadButton")).click(); // Create FluentWait instance Wait<WebDriver> wait = new FluentWait<>(driver) .withTimeout(Duration.ofSeconds(10)) .pollingEvery(Duration.ofMillis(500)) .ignoring(NoSuchElementException.class); // Wait for the dynamic element to be visible WebElement dynamicElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElement"))); // Assertion: element is displayed if (dynamicElement.isDisplayed()) { System.out.println("Test Passed: Dynamic element is visible."); } else { System.out.println("Test Failed: Dynamic element is not visible."); } } finally { driver.quit(); } } }
This code starts by setting up the Chrome WebDriver and opening the test page.
It clicks the button with id loadButton to trigger loading the dynamic element.
Then, it creates a FluentWait object with a timeout of 10 seconds and polling every 500 milliseconds. It ignores NoSuchElementException during waiting.
The wait uses ExpectedConditions.visibilityOfElementLocated to wait until the dynamic element with id dynamicElement is visible.
Finally, it checks if the element is displayed and prints the test result.
The driver.quit() in finally ensures the browser closes even if an error occurs.
Now add data-driven testing to click different buttons with ids 'loadButton1', 'loadButton2', 'loadButton3' and verify their respective dynamic elements appear.