Unexpected alert handling in Selenium Java - Build an Automation Script
import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.NoAlertPresentException; 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 UnexpectedAlertHandlingTest { 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 { // Navigate to form page driver.get("https://example.com/form"); // Enter username WebElement usernameInput = wait.until(ExpectedConditions.elementToBeClickable(By.id("username"))); usernameInput.sendKeys("testuser"); // Click submit button WebElement submitBtn = driver.findElement(By.id("submitBtn")); submitBtn.click(); // Wait briefly for alert presence try { wait.until(ExpectedConditions.alertIsPresent()); Alert alert = driver.switchTo().alert(); alert.accept(); } catch (NoAlertPresentException e) { // No alert appeared, continue } // Verify URL changed to success page wait.until(ExpectedConditions.urlToBe("https://example.com/form-success")); String currentUrl = driver.getCurrentUrl(); if (!"https://example.com/form-success".equals(currentUrl)) { throw new AssertionError("Expected URL to be https://example.com/form-success but was " + currentUrl); } System.out.println("Test passed: Unexpected alert handled and success page loaded."); } finally { driver.quit(); } } }
This test script uses Selenium WebDriver with Java to automate the manual test case.
First, it opens the form page and waits until the username input is clickable, then enters 'testuser'.
Next, it clicks the submit button.
After clicking, it waits explicitly for an alert to appear. If an alert appears, it switches to it and accepts it. If no alert appears, it catches the exception and continues without failing.
Finally, it waits until the URL changes to the expected success page URL and asserts this condition. If the URL is not as expected, it throws an assertion error.
The test ends by quitting the browser.
This approach uses explicit waits and proper exception handling to manage unexpected alerts gracefully.
Now add data-driven testing with 3 different usernames to submit the form and handle alerts