Handling Java Alerts using Selenium Webdriver
Understanding Java Alerts ๐ค
Java Alerts are used to convey important information, warnings, or prompt user interaction. They can appear as simple informational messages, confirmations, or input prompts.
Types of Java Alerts:
Alerts: Simple notifications that require acknowledgment.
Confirmations: Alerts with options to confirm or cancel.
Prompts: Alerts that prompt the user to enter input.
Selenium Commands for Java Alerts ๐น
Alert Interface:
Selenium provides the Alert interface to interact with Java Alerts. Here are some essential methods:
Switch to Alert:
Alert alert = driver.switchTo().alert();
Accept Alert (OK/Yes):
alert.accept();
Dismiss Alert (Cancel/No):
alert.dismiss();
Get Alert Text:
String alertText = alert.getText();
Enter Text in Prompt:
alert.sendKeys("YourInput");
Handling Different Alert Types ๐
Simple Alerts: Simple alerts require only acknowledgment. Use
accept()
to close them.Alert simpleAlert = driver.switchTo().alert(); simpleAlert.accept();
Confirm Alerts: Confirm alerts have options to confirm or cancel. Use
accept()
for confirmation anddismiss()
for cancellation.Alert confirmAlert = driver.switchTo().alert(); confirmAlert.accept(); // Confirm // OR confirmAlert.dismiss(); // Cancel
Prompt Alerts: Prompt alerts prompt the user to enter input. Use
sendKeys()
to enter text andaccept()
to confirm.Alert promptAlert = driver.switchTo().alert(); promptAlert.sendKeys("YourInput"); promptAlert.accept();
Example: Handling a Login Alert ๐
Consider a scenario where a website prompts an alert upon incorrect login credentials. You can handle it like this:
// Locate login elements and trigger login attempt
driver.findElement(By.id("username")).sendKeys("yourUsername");
driver.findElement(By.id("password")).sendKeys("wrongPassword");
driver.findElement(By.id("loginBtn")).click();
// Handle alert
Alert loginAlert = driver.switchTo().alert();
String alertText = loginAlert.getText();
System.out.println("Alert Text: " + alertText);
loginAlert.accept();
Conclusion ๐
Mastering Java Alerts is essential for robust Selenium test automation. With the Alert interface, you can seamlessly handle alerts of different types, ensuring your automated tests handle pop-ups gracefully. Happy testing! ๐๐ฆ