ExpectedConditions class 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; public class ExpectedConditionsTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com/startpage"); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement submitButton = wait.until(ExpectedConditions.elementToBeClickable(By.id("submitBtn"))); submitButton.click(); wait.until(ExpectedConditions.urlToBe("https://example.com/nextpage")); String currentUrl = driver.getCurrentUrl(); if (!currentUrl.equals("https://example.com/nextpage")) { throw new AssertionError("URL after click is not as expected. Found: " + currentUrl); } System.out.println("Test Passed: Button clicked after becoming clickable and URL verified."); } catch (Exception e) { e.printStackTrace(); } finally { driver.quit(); } } }
This code uses Selenium WebDriver with Java to automate the test case.
First, it opens the browser and navigates to the start page.
Then, it creates a WebDriverWait object with a 10-second timeout.
It waits explicitly for the button with id submitBtn to become clickable using ExpectedConditions.elementToBeClickable.
Once clickable, it clicks the button.
After clicking, it waits until the URL changes to the expected next page URL using ExpectedConditions.urlToBe.
It then asserts that the current URL matches the expected URL.
If all steps pass, it prints a success message.
The try-finally block ensures the browser closes even if an error occurs.
Now add data-driven testing to wait for and click buttons with ids 'submitBtn1', 'submitBtn2', and 'submitBtn3' on the same page, verifying navigation after each click.