Bird
Raised Fist0
Selenium Javatesting~10 mins

Unexpected alert handling in Selenium Java - Test Execution Trace

Choose your learning style10 modes available
Test Overview

This test checks how the Selenium WebDriver handles an unexpected alert popup during navigation. It verifies that the alert is detected and accepted to allow the test to continue smoothly.

Test Code - JUnit 5 with Selenium WebDriver
Selenium Java
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class UnexpectedAlertHandlingTest {
    private WebDriver driver;
    private WebDriverWait wait;

    @BeforeEach
    public void setUp() {
        driver = new ChromeDriver();
        wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    }

    @Test
    public void testHandleUnexpectedAlert() {
        driver.get("https://example.com/page_with_unexpected_alert");

        try {
            // Wait for alert to be present
            Alert alert = wait.until(ExpectedConditions.alertIsPresent());
            // Accept the alert
            alert.accept();
        } catch (TimeoutException e) {
            // No alert appeared, continue
        }

        // After alert is handled, verify page title
        String title = driver.getTitle();
        assertEquals("Expected Page Title", title);
    }

    @AfterEach
    public void tearDown() {
        if (driver != null) {
            driver.quit();
        }
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensChrome browser window is open and ready—PASS
2Navigates to https://example.com/page_with_unexpected_alertBrowser loads the page which triggers an unexpected alert popup—PASS
3Waits up to 10 seconds for alert to be present using WebDriverWait and ExpectedConditions.alertIsPresent()Alert popup is detected on the pageAlert presence is verifiedPASS
4Accepts the alert popup by calling alert.accept()Alert popup is closed, page is visible and interactive—PASS
5Retrieves the page title using driver.getTitle()Page title is fetched from the browserPage title equals 'Expected Page Title'PASS
6Test ends and browser closesBrowser window is closed—PASS
Failure Scenario
Failing Condition: Alert does not appear and test tries to accept a non-existent alert or page title does not match expected
Execution Trace Quiz - 3 Questions
Test your understanding
What Selenium method is used to wait for the unexpected alert to appear?
Await.until(ExpectedConditions.alertIsPresent())
Bdriver.findElement(By.alert())
Cdriver.switchTo().alert() without wait
Ddriver.getAlert()
Key Result
Always use explicit waits like WebDriverWait with ExpectedConditions to handle unexpected alerts gracefully, preventing test failures due to timing issues.

Practice

(1/5)
1. What is the main reason to handle unexpected alerts in Selenium tests?
easy
A. To prevent tests from stopping abruptly due to unhandled pop-ups
B. To improve the speed of test execution
C. To change the browser window size automatically
D. To log user actions during the test

Solution

  1. Step 1: Understand unexpected alerts impact

    Unexpected alerts block the browser and stop test execution if not handled.
  2. Step 2: Purpose of handling alerts

    Handling alerts allows the test to continue smoothly without interruption.
  3. Final Answer:

    To prevent tests from stopping abruptly due to unhandled pop-ups -> Option A
  4. Quick Check:

    Unexpected alerts stop tests = Handle alerts [OK]
Hint: Handle alerts to keep tests running without interruption [OK]
Common Mistakes:
  • Thinking alerts only slow tests, not stop them
  • Confusing alert handling with browser resizing
  • Assuming alerts are for logging only
2. Which Selenium Java code snippet correctly switches to an alert and accepts it?
easy
A. driver.switchTo().alert().dismiss();
B. driver.alert().switchTo().accept();
C. driver.switchTo().alert().accept();
D. driver.switchTo().alert().sendKeys();

Solution

  1. Step 1: Identify correct alert switching syntax

    The correct method to switch to alert is driver.switchTo().alert()
  2. Step 2: Accept the alert

    Calling accept() on the alert confirms it and closes the pop-up.
  3. Final Answer:

    driver.switchTo().alert().accept(); -> Option C
  4. Quick Check:

    Switch to alert then accept = driver.switchTo().alert().accept() [OK]
Hint: Use driver.switchTo().alert().accept() to accept alerts [OK]
Common Mistakes:
  • Reversing switchTo() and alert() calls
  • Using dismiss() instead of accept() when accept is needed
  • Calling sendKeys() without parameters
3. What will happen if the following code runs when an unexpected alert is present?
driver.findElement(By.id("submit")).click();
driver.switchTo().alert().dismiss();
driver.findElement(By.id("next")).click();
medium
A. The alert will be accepted instead of dismissed
B. No alert handling occurs and test throws NoAlertPresentException
C. The test will fail at clicking submit due to alert presence
D. The alert will be dismissed and the next button clicked successfully

Solution

  1. Step 1: Click triggers alert

    Clicking submit may cause an alert to appear unexpectedly.
  2. Step 2: Alert is dismissed explicitly

    driver.switchTo().alert().dismiss() closes the alert, allowing further actions.
  3. Step 3: Next element interaction

    After dismissing alert, clicking next proceeds without interruption.
  4. Final Answer:

    The alert will be dismissed and the next button clicked successfully -> Option D
  5. Quick Check:

    Dismiss alert then continue = success [OK]
Hint: Dismiss alert before next action to avoid test failure [OK]
Common Mistakes:
  • Assuming alert auto-dismisses without code
  • Expecting accept() instead of dismiss() here
  • Ignoring NoAlertPresentException possibility
4. Identify the error in this code snippet handling unexpected alerts:
try {
  driver.findElement(By.id("save")).click();
} catch (NoAlertPresentException e) {
  driver.switchTo().alert().accept();
}
medium
A. NoAlertPresentException should be caught after alert handling
B. Alert handling code is inside catch for wrong exception
C. Accept() should be replaced with dismiss()
D. Try block should include alert handling, not catch

Solution

  1. Step 1: Understand exception usage

    NoAlertPresentException occurs when alert is not present but code tries to switch to alert.
  2. Step 2: Analyze catch block logic

    Alert handling code is wrongly placed inside catch for NoAlertPresentException, which means alert is not present.
  3. Step 3: Correct approach

    Alert handling should be in try block or catch should handle different exception like UnhandledAlertException.
  4. Final Answer:

    Alert handling code is inside catch for wrong exception -> Option B
  5. Quick Check:

    Catch wrong exception for alert handling = error [OK]
Hint: Catch UnhandledAlertException, not NoAlertPresentException for alerts [OK]
Common Mistakes:
  • Catching NoAlertPresentException to handle alert
  • Placing alert.accept() inside catch for missing alert
  • Confusing accept() and dismiss() usage
5. You want to write a Selenium Java method that safely clicks a button even if an unexpected alert appears. Which code snippet correctly handles this scenario?
hard
A. try { driver.findElement(By.id("btn")).click(); } catch (UnhandledAlertException e) { driver.switchTo().alert().accept(); driver.findElement(By.id("btn")).click(); }
B. driver.findElement(By.id("btn")).click(); driver.switchTo().alert().accept();
C. driver.switchTo().alert().accept(); driver.findElement(By.id("btn")).click();
D. try { driver.switchTo().alert().accept(); } catch (NoAlertPresentException e) { driver.findElement(By.id("btn")).click(); }

Solution

  1. Step 1: Understand unexpected alert during click

    Clicking the button may cause an unexpected alert, throwing UnhandledAlertException.
  2. Step 2: Use try-catch to handle alert and retry click

    Catch UnhandledAlertException, accept alert, then retry clicking the button to ensure action completes.
  3. Step 3: Verify other options

    driver.findElement(By.id("btn")).click(); driver.switchTo().alert().accept(); and C do not handle exceptions; try { driver.switchTo().alert().accept(); } catch (NoAlertPresentException e) { driver.findElement(By.id("btn")).click(); } tries alert first which may not exist before click.
  4. Final Answer:

    try { driver.findElement(By.id("btn")).click(); } catch (UnhandledAlertException e) { driver.switchTo().alert().accept(); driver.findElement(By.id("btn")).click(); } -> Option A
  5. Quick Check:

    Catch alert exception, accept, retry click = safe handling [OK]
Hint: Catch alert exception, accept alert, then retry action [OK]
Common Mistakes:
  • Not retrying click after alert acceptance
  • Handling alert before click without exception
  • Catching wrong exception types
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard