Sometimes, pop-up alerts appear suddenly during testing. Handling them properly helps tests run smoothly without errors.
Unexpected alert handling in Selenium Java
Introduction
Syntax
Selenium Java
Alert alert = driver.switchTo().alert(); alert.accept(); // to click OK alert.dismiss(); // to click Cancel String alertText = alert.getText();
Use driver.switchTo().alert() to focus on the alert.
accept() clicks OK, dismiss() clicks Cancel or closes the alert.
Examples
Selenium Java
Alert alert = driver.switchTo().alert(); alert.accept();
Selenium Java
Alert alert = driver.switchTo().alert(); alert.dismiss();
Selenium Java
Alert alert = driver.switchTo().alert(); String message = alert.getText(); System.out.println(message);
Sample Program
This test opens a page with a button that triggers an alert. It switches to the alert, prints its message, then accepts it to continue.
Selenium Java
import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class AlertHandlingTest { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert"); // Switch to iframe where the alert button is driver.switchTo().frame("iframeResult"); // Click the button to trigger alert driver.findElement(By.tagName("button")).click(); // Switch to alert Alert alert = driver.switchTo().alert(); // Get alert text String alertText = alert.getText(); System.out.println("Alert says: " + alertText); // Accept the alert alert.accept(); // Close browser driver.quit(); } }
Important Notes
Always switch to the alert before interacting with it, or Selenium will throw an error.
If you don't handle unexpected alerts, your test may stop abruptly.
Use try-catch blocks to handle alerts that may or may not appear.
Summary
Unexpected alerts can stop tests if not handled.
Use driver.switchTo().alert() to work with alerts.
Accept or dismiss alerts to continue testing smoothly.
Practice
1. What is the main reason to handle unexpected alerts in Selenium tests?
easy
Solution
Step 1: Understand unexpected alerts impact
Unexpected alerts block the browser and stop test execution if not handled.Step 2: Purpose of handling alerts
Handling alerts allows the test to continue smoothly without interruption.Final Answer:
To prevent tests from stopping abruptly due to unhandled pop-ups -> Option AQuick 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
Solution
Step 1: Identify correct alert switching syntax
The correct method to switch to alert is driver.switchTo().alert()Step 2: Accept the alert
Calling accept() on the alert confirms it and closes the pop-up.Final Answer:
driver.switchTo().alert().accept(); -> Option CQuick 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
Solution
Step 1: Click triggers alert
Clicking submit may cause an alert to appear unexpectedly.Step 2: Alert is dismissed explicitly
driver.switchTo().alert().dismiss() closes the alert, allowing further actions.Step 3: Next element interaction
After dismissing alert, clicking next proceeds without interruption.Final Answer:
The alert will be dismissed and the next button clicked successfully -> Option DQuick 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
Solution
Step 1: Understand exception usage
NoAlertPresentException occurs when alert is not present but code tries to switch to alert.Step 2: Analyze catch block logic
Alert handling code is wrongly placed inside catch for NoAlertPresentException, which means alert is not present.Step 3: Correct approach
Alert handling should be in try block or catch should handle different exception like UnhandledAlertException.Final Answer:
Alert handling code is inside catch for wrong exception -> Option BQuick 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
Solution
Step 1: Understand unexpected alert during click
Clicking the button may cause an unexpected alert, throwing UnhandledAlertException.Step 2: Use try-catch to handle alert and retry click
Catch UnhandledAlertException, accept alert, then retry clicking the button to ensure action completes.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.Final Answer:
try { driver.findElement(By.id("btn")).click(); } catch (UnhandledAlertException e) { driver.switchTo().alert().accept(); driver.findElement(By.id("btn")).click(); } -> Option AQuick 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
10 questions ~5 mineasy hard
