This test opens a page with JavaScript alerts, clicks a button to show an alert, reads and prints the alert text, accepts the alert, then prints the result message on the page.
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class AlertTest {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("https://the-internet.herokuapp.com/javascript_alerts");
// 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();
String alertMessage = alert.getText();
System.out.println("Alert says: " + alertMessage);
alert.accept();
// Verify result text
String result = driver.findElement(By.id("result")).getText();
System.out.println("Result text: " + result);
driver.quit();
}
}