Date picker strategies 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 DatePickerTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); try { driver.get("https://example.com/date-picker"); // Locate the date picker input field by id WebElement dateInput = wait.until(ExpectedConditions.elementToBeClickable(By.id("datePickerInput"))); // Click to open the date picker widget dateInput.click(); // Wait for the calendar widget to be visible WebElement calendarWidget = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("calendarWidget"))); // Navigate to the desired month and year if needed // For simplicity, assume current month is correct // Select the 15th day WebElement day15 = calendarWidget.findElement(By.xpath(".//td[@data-day='15']")); day15.click(); // Verify the input field value is updated to 15th (format: yyyy-MM-dd) String selectedDate = dateInput.getAttribute("value"); if (!selectedDate.equals("2024-06-15")) { throw new AssertionError("Date picker input value mismatch. Expected: 2024-06-15, Found: " + selectedDate); } System.out.println("Test Passed: Date selected correctly."); } finally { driver.quit(); } } }
This test script uses Selenium WebDriver with Java to automate selecting a date from a date picker widget.
First, it opens the web page and waits until the date picker input field is clickable. Then it clicks the input to open the calendar widget and waits for the calendar to appear.
It selects the 15th day by locating the calendar cell with a data attribute for day 15. After clicking the date, it verifies that the input field's value matches the expected date string.
Explicit waits ensure elements are ready before interacting, avoiding flaky tests. Using meaningful locators like id and data attributes makes the test more stable. The test ends by closing the browser.
Now add data-driven testing to select three different dates: 5th, 15th, and 25th of the current month.