Hello karthik,
Handling alerts manually is a tedious task. To reduce human intervention and ease this task, Selenium provides a wide range of functionalities and methods to handle alerts.
The following methods are useful to handle alerts in selenium:
1. Void dismiss(): This method is used when ‘Cancel’ button is clicked in the alert box.
driver.switchTo().alert().dismiss();
2. Void accept(): This method is used to click on the ‘OK’ button of the alert.
driver.switchTo().alert().accept();
3. String getText(): This method is used to capture the alert message.
driver.switchTo().alert().getText();
4. Void sendKeys(String stringToSend): This method is used to send data to the alert box.
driver.switchTo().alert().sendKeys("Text");
Here how exactly alerts in selenium works with the help of an example.
Let’s write a Selenium test script to handle alerts.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.Alert;
public class AlertHandlingDemo {
public static void main(String[] args) throws NoAlertPresentException,InterruptedException {
System.setProperty("webdriver.chrome.driver","Path_of_Chrome_Driver"); //mention dummy path or variable that stores chrome driver path
WebDriver driver = new ChromeDriver(); driver.get("https://www.edureka.co/users/sign_up");
driver.findElement(By.id("user_full_name")).sendKeys("username"); driver.findElement(By.id("input-lg text user_email_ajax")).sendKeys("username.xyz.net");
driver.findElement(By.id("user_password")).sendKeys("Your_Password");
driver.findElement(By.id("user_submit")).click();
Thread.sleep(5000);
Alert alert = driver.switchTo().alert(); // switch to alert
String alertMessage= driver.switchTo().alert().getText(); // capture alert message
System.out.println(alertMessage); // Print Alert Message
Thread.sleep(5000);
alert.accept();
}
}
When you execute the above code, it navigates through the Sign up page, inputs the necessary details, hits the Sign me up button and throws the alert.
Next, the driver will switch to alert, try to capture the alert message, and then display the message.
Wish to know about Selenium Automation Testing with Java, have a glance at the detailed Selenium Tutorial.
Thank You!!