Selenium WebDriver- Handling AlertsIn this section, you will learn how to handle alerts in Selenium WebDriver. Selenium WebDriver provides three methods to accept and reject the Alert depending on the Alert types. 1. void dismiss()This method is used to click on the 'Cancel' button of the alert. Syntax: 2. void accept()This method is used to click on the 'Ok' button of the alert. Syntax: 3. String getText()This method is used to capture the alert message. Syntax: 4. void sendKeys(String stringToSend)This method is used to send some data to the alert box. Syntax: Let us consider a test case in which we will automate the following scenarios:
We will create our test case step by step in order to give you a complete understanding of how to handle alerts in WebDriver. Step1. Launch Eclipse IDE and open the existing test suite "Demo_Test" which we have created in earlier sessions of this tutorial. Step2. Right click on the "src" folder and create a new Class File from New >Class. Give your Class name as "alert_test" and click on "Finish" button. Step3. Let's get to the coding ground.
Here is the sample code to set system property for Gecko driver:
Here is the sample code to initialize gecko driver using DesiredCapabilities class. Combining both of the above code blocks, we will get the code snippet to launch Firefox browser.
Here is the sample code to navigate to the desired URL: The complete code till now will look something like this: Step4. Now, we will try to locate the "Generate Alert Box" and "Generate Confirm Box" in order to perform alert handling operation. As we know that locating an element involves inspection of its HTML codes. Follow the steps given below to locate the drop-down menu on the sample web page.
Similarly, we will inspect the "Generate Confirm box" button.
Step5. To automate our third and fourth test scenario, we need to write the code which click and accept the Generate Alert box as well as click and accept the Generate Confirm box. Given below is the code snippet to automate our third and fourth test scenario. Thus, our final test script will look something like this: Upon execution, the above test script will launch the Firefox browser and automate all the test scenarios.
Next TopicScrolling a Web Page
|