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.
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.
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(); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Chrome browser window is open and ready | - | PASS |
| 2 | Navigates to https://example.com/page_with_unexpected_alert | Browser loads the page which triggers an unexpected alert popup | - | PASS |
| 3 | Waits up to 10 seconds for alert to be present using WebDriverWait and ExpectedConditions.alertIsPresent() | Alert popup is detected on the page | Alert presence is verified | PASS |
| 4 | Accepts the alert popup by calling alert.accept() | Alert popup is closed, page is visible and interactive | - | PASS |
| 5 | Retrieves the page title using driver.getTitle() | Page title is fetched from the browser | Page title equals 'Expected Page Title' | PASS |
| 6 | Test ends and browser closes | Browser window is closed | - | PASS |