0
0
Selenium Javatesting~15 mins

Unexpected alert handling in Selenium Java - Build an Automation Script

Choose your learning style9 modes available
Handle unexpected alert during form submission
Preconditions (2)
Step 1: Enter 'testuser' in the username input field
Step 2: Click the submit button
Step 3: If an unexpected alert appears, accept it
Step 4: Verify that the page URL changes to 'https://example.com/form-success'
✅ Expected Result: The unexpected alert is accepted without test failure and the page navigates to the success URL
Automation Requirements - Selenium WebDriver with Java
Assertions Needed:
Verify the alert is present and accepted
Verify the current URL is 'https://example.com/form-success'
Best Practices:
Use explicit waits to detect alert presence
Use try-catch to handle NoAlertPresentException
Avoid Thread.sleep; use WebDriverWait
Use By.id locator strategy for elements
Automated Solution
Selenium Java
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.

Common Mistakes - 4 Pitfalls
Using Thread.sleep() to wait for alert
Not handling NoAlertPresentException when switching to alert
Using brittle XPath locators for username and submit button
Not verifying the URL after alert handling
Bonus Challenge

Now add data-driven testing with 3 different usernames to submit the form and handle alerts

Show Hint