Alert accept and dismiss in Selenium Java - Build an Automation Script
import org.openqa.selenium.Alert; import org.openqa.selenium.By; 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 org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.time.Duration; public class AlertAcceptDismissTest { private WebDriver driver; private WebDriverWait wait; @BeforeClass public void setUp() { // Set path to chromedriver if needed driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.get("https://example.com/alert-test"); // Replace with actual URL } @Test public void testAlertAccept() { WebElement alertButton = driver.findElement(By.id("alertButton")); alertButton.click(); // Wait for alert to be present Alert alert = wait.until(ExpectedConditions.alertIsPresent()); // Verify alert text String alertText = alert.getText(); Assert.assertEquals(alertText, "Are you sure you want to proceed?", "Alert text mismatch"); // Accept the alert alert.accept(); // Verify success message displayed after accepting WebElement message = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("message"))); Assert.assertEquals(message.getText(), "You accepted the alert!", "Success message mismatch after accept"); } @Test(dependsOnMethods = "testAlertAccept") public void testAlertDismiss() { WebElement alertButton = driver.findElement(By.id("alertButton")); alertButton.click(); Alert alert = wait.until(ExpectedConditions.alertIsPresent()); // Verify alert text String alertText = alert.getText(); Assert.assertEquals(alertText, "Are you sure you want to proceed?", "Alert text mismatch"); // Dismiss the alert alert.dismiss(); // Verify cancellation message displayed after dismissing WebElement message = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("message"))); Assert.assertEquals(message.getText(), "You dismissed the alert!", "Cancellation message mismatch after dismiss"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
This test class uses Selenium WebDriver with TestNG to automate alert accept and dismiss actions.
setUp(): Opens the browser and navigates to the test page.
testAlertAccept(): Clicks the button to trigger alert, waits for alert, verifies alert text, accepts alert, then verifies the success message.
testAlertDismiss(): Clicks the button again, waits for alert, verifies alert text, dismisses alert, then verifies the cancellation message.
Explicit waits ensure the alert and messages are present before interacting or asserting. Assertions check the alert text and messages to confirm correct behavior. The @AfterClass method closes the browser after tests.
Now add data-driven testing with 3 different alert messages and expected results
Practice
accept() method do when called on a JavaScript alert in Selenium?Solution
Step 1: Understand alert interaction methods
Theaccept()method is used to click the OK button on an alert popup.Step 2: Differentiate from dismiss()
Thedismiss()method clicks Cancel, soaccept()must click OK.Final Answer:
Clicks the OK button on the alert -> Option AQuick Check:
accept() = OK click [OK]
- Confusing accept() with dismiss()
- Thinking accept() closes the browser
- Assuming accept() throws an exception
Solution
Step 1: Identify the method to dismiss alert
The method to click Cancel on an alert isdismiss().Step 2: Confirm correct syntax for switching and dismissing
The correct chain isdriver.switchTo().alert().dismiss();to dismiss the alert.Final Answer:
driver.switchTo().alert().dismiss(); -> Option AQuick Check:
dismiss() = Cancel click [OK]
- Using accept() instead of dismiss() to cancel
- Using non-existent methods like close() or cancel()
- Missing switchTo().alert() before calling dismiss()
driver.switchTo().alert().accept();
System.out.println("Alert handled successfully");Solution
Step 1: Understand alert acceptance effect
Callingaccept()closes the alert, allowing the next line to execute.Step 2: Check output after alert handling
Since alert is accepted,System.out.printlnruns and prints the message.Final Answer:
Alert handled successfully -> Option BQuick Check:
accept() closes alert, next line prints [OK]
- Expecting exception after accept()
- Thinking alert blocks print statement
- Confusing accept() with dismiss() effect
Alert alert = driver.switchTo().alert(); alert.accept(); alert.dismiss();
Solution
Step 1: Understand alert lifecycle after accept()
Onceaccept()is called, the alert is closed and no longer available.Step 2: Calling dismiss() after accept() is invalid
Trying to dismiss the same alert after accepting it causes an error because alert is gone.Final Answer:
Cannot call dismiss() after accept() on the same alert instance -> Option DQuick Check:
accept() closes alert, no dismiss() after [OK]
- Calling dismiss() after accept() on same alert
- Assuming alert stays open after accept()
- Using non-existent cancel() method
Solution
Step 1: Check alert text for "Delete" substring
Usealert.getText().contains("Delete")to detect if alert text includes "Delete".Step 2: Dismiss alert if condition true, else accept
If text contains "Delete", calldismiss()to click Cancel; otherwise, callaccept().Final Answer:
Alert alert = driver.switchTo().alert(); if (alert.getText().contains("Delete")) { alert.dismiss(); } else { alert.accept(); } -> Option CQuick Check:
Use contains() and dismiss() for conditional cancel [OK]
- Using == instead of contains() for string check
- Calling dismiss() before checking alert text
- Calling accept() and dismiss() both without condition
Ready to prove it?
Pass the test and this pattern moves unknown
