Test Overview
This test demonstrates how to create and use a custom ExpectedCondition in Selenium WebDriver with Java. It waits for a specific element's text to become "Loaded" before proceeding, verifying the page state dynamically.
This test demonstrates how to create and use a custom ExpectedCondition in Selenium WebDriver with Java. It waits for a specific element's text to become "Loaded" before proceeding, verifying the page state dynamically.
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.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; public class CustomExpectedConditionTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com/loadingpage"); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); ExpectedCondition<Boolean> textIsLoaded = new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { WebElement element = d.findElement(By.id("status")); return "Loaded".equals(element.getText()); } public String toString() { return "text to be 'Loaded' in element with id 'status'"; } }; wait.until(textIsLoaded); WebElement statusElement = driver.findElement(By.id("status")); assert "Loaded".equals(statusElement.getText()) : "Status text is not 'Loaded'"; System.out.println("Test Passed: Status text is 'Loaded'."); } finally { driver.quit(); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and ChromeDriver is initialized | Browser window opens with a blank page | - | PASS |
| 2 | Navigates to https://example.com/loadingpage | Page loads with element id='status' showing initial text (e.g., 'Loading...') | - | PASS |
| 3 | Waits up to 10 seconds for element with id 'status' text to become 'Loaded' using custom ExpectedCondition | Page updates element text from 'Loading...' to 'Loaded' dynamically | Checks if element text equals 'Loaded' | PASS |
| 4 | Finds element with id 'status' and asserts its text is 'Loaded' | Element text is 'Loaded' | assert "Loaded".equals(statusElement.getText()) | PASS |
| 5 | Prints success message and closes browser | Browser closes | - | PASS |