Sunday, 30 September 2012

Handling Alerts in Selenium/WebDriver

Hello All,

It has been a long long time, when i wrote something for you guys on my blog. Got some time to write something, so today it will be related to handling alerts in selenium/webdriver.This post is written keeping Selenium 2.0 in my mind. So it may not hold good for Selenium RC users.

Selenium can handle  java script alerts in a very effective manner but it can not handle modal alert box which gets created by OS itself e.g.:  java script error message alert. Now how do you handle these java script alerts, what can you do with those alerts, lets see one by one with the code.

Let us take a Scenario as an example -:
 Select a object from the page, Click on Delete button. It triggers a alert saying "Object is going to be deleted from the database, Click OK to Confirm or Cancel to Cancel the Operation".

We need to test the message of the Alert, Clicking Ok and Clicking Cancel also.
Steps to be Performed
=========================
Select the Object to delete from the page.
Click on Delete button, it triggers the Alert message.




/* Code to switch the control to Alert message*/
Alert testAlrt=driver.switchTo().alert();
testAlrt is the Controlling object of the Alert. Now you can use this object to Accept/get Text/Dismiss the alert.

/* To get the text from the alert */
String sAltText=testAlrt.getText();

/* To Accept any alert, it means Clicking OK button */
testAlrt.accept();

/* To dismiss any alert, It means Clicking Cancel button */
testAlrt.dismiss();

/* If the Alerts gets created using Ajax call, then you may need to wait till the Alert present */
WebDriverWait wdWait= new WebDriverWait(driver, 10);
wdWait.until(ExpectedConditions.alertIsPresent());



This is all about handling Alerts in your Selenium test scripts. Please give back a feedback about the post.

Thanks!!

Related Posts

Related Posts...