Prompt alert text entry in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.Alert; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.chrome.ChromeDriver; 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 PromptAlertTest { WebDriver driver; WebDriverWait wait; @BeforeClass public void setUp() { driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.get("https://example.com/prompt-alert"); // Replace with actual URL } @Test public void testPromptAlertTextEntry() { // Click the button that triggers the prompt alert WebElement promptButton = driver.findElement(By.id("promptButton")); promptButton.click(); // Wait for the alert to be present Alert promptAlert = wait.until(ExpectedConditions.alertIsPresent()); // Verify alert is displayed Assert.assertNotNull(promptAlert, "Prompt alert should be present"); // Enter text into the prompt alert String inputText = "HelloTest"; promptAlert.sendKeys(inputText); // Accept the alert promptAlert.accept(); // Verify the entered text appears on the page WebElement resultText = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("result"))); Assert.assertEquals(resultText.getText(), inputText, "The result text should match the entered prompt text"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
This test script uses Selenium WebDriver with Java and TestNG for assertions.
First, it opens the target page in the setUp method.
The test clicks the button with id promptButton to open the prompt alert.
It waits explicitly for the alert to appear using WebDriverWait and ExpectedConditions.alertIsPresent().
Once the alert is present, it sends the text HelloTest to the prompt input field and accepts the alert.
Finally, it waits for the result element with id result to be visible and asserts that its text matches the entered input.
The tearDown method closes the browser after the test.
This approach ensures the test waits properly for elements and alerts, uses clear locators, and verifies the expected behavior.
Now add data-driven testing with 3 different input texts for the prompt alert