Test Overview
This test opens a web page with a JavaScript alert, then it accepts the alert and verifies the confirmation message. Next, it triggers a confirm alert, dismisses it, and verifies the cancellation message.
This test opens a web page with a JavaScript alert, then it accepts the alert and verifies the confirmation message. Next, it triggers a confirm alert, dismisses it, and verifies the cancellation message.
import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; 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 AlertAcceptDismissTest { WebDriver driver; @BeforeEach public void setUp() { driver = new ChromeDriver(); driver.get("https://the-internet.herokuapp.com/javascript_alerts"); } @Test public void testAlertAcceptAndDismiss() { // Click button to trigger alert driver.findElement(By.xpath("//button[text()='Click for JS Alert']")).click(); // Switch to alert and accept it Alert alert = driver.switchTo().alert(); alert.accept(); // Verify result text after accepting alert String resultText = driver.findElement(By.id("result")).getText(); assertEquals("You successfully clicked an alert", resultText); // Click button to trigger confirm alert driver.findElement(By.xpath("//button[text()='Click for JS Confirm']")).click(); // Switch to alert and dismiss it Alert confirmAlert = driver.switchTo().alert(); confirmAlert.dismiss(); // Verify result text after dismissing confirm alert String confirmResult = driver.findElement(By.id("result")).getText(); assertEquals("You clicked: Cancel", confirmResult); } @AfterEach public void tearDown() { driver.quit(); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and Chrome browser opens | Browser is open at https://the-internet.herokuapp.com/javascript_alerts | - | PASS |
| 2 | Finds and clicks the 'Click for JS Alert' button | JavaScript alert popup appears | - | PASS |
| 3 | Switches to alert and accepts it | Alert is closed, page shows result message | Verify result text is 'You successfully clicked an alert' | PASS |
| 4 | Finds and clicks the 'Click for JS Confirm' button | JavaScript confirm alert popup appears | - | PASS |
| 5 | Switches to confirm alert and dismisses it | Confirm alert is closed, page shows result message | Verify result text is 'You clicked: Cancel' | PASS |
| 6 | Test ends and browser closes | Browser closed | - | PASS |