How to Handle Alerts in Selenium WebDriver

Last updated on Dec 02 2021
Swaminathan M

Table of Contents

How to Handle Alerts in Selenium WebDriver

In this blog , you’ll find out how to handle alerts in Selenium WebDriver.

Selenium WebDriver provides three methods to simply accept and reject the Alert counting on the Alert types.

1. void dismiss()
This method is employed to click on the ‘Cancel’ button of the alert.
Syntax:

1. driver.switchTo().alert().dismiss();
2. void accept()

This method is employed to click on the ‘Ok’ button of the alert.
Syntax:

1. driver.switchTo().alert().accept();
3. String getText()

This method is employed to capture the alert message.
Syntax:

1. driver.switchTo().alert().getText();
4. void sendKeys(String stringToSend)

This method is employed to send some data to the alert box.
Syntax:
1. driver.switchTo().alert().sendKeys(“Text”);

Let us consider a test suit during which we’ll automate the subsequent scenarios:
• Invoke Firefox Browser
• Open URL: https://www.testandquiz.com/selenium/testing.html
• Click on the “Generate Alert box” button
• Click on the “Generate Confirm box” button
• Close the browser

We will create our test suit step by step so as to offer you an entire understanding of the way to handle alerts in WebDriver.

Step1. Launch Eclipse IDE and open the prevailing test suite “Demo_Test” which we’ve created in earlier sessions of this tutorial.
Step2. Right click on the “src” folder and make a replacement Class File from New >Class.

hand 1
New Class

Give your Class name as “alert_test” and click on on “Finish” button.

hand 2
alert_test

Step3. Let’s get to the coding ground.

• To invoke Firefox browser, we’d like to download Gecko driver and set the system property for Gecko driver. we’ve already discussed this in earlier sessions of this tutorial. you’ll refer “Running test on Firefox Browser” to find out the way to download and set System property for Firefox driver.

Here is that the sample code to line system property for Gecko driver:

1. // System Property for Gecko Driver
2. stem.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" );

• After that we’ve to initialize Gecko Driver using Desired Capabilities Class.
Here is that the sample code to initialize gecko driver using DesiredCapabilities class.

1. // Initialize Gecko Driver using Desired Capabilities Class
2. DesiredCapabilities capabilities = DesiredCapabilities.firefox();
3. capabilities.setCapability("marionette",true);
4. ebDriver driver= new FirefoxDriver(capabilities);

Combining both of the above code blocks, we’ll get the code snippet to launch Firefox browser.

1. // System Property for Gecko Driver
2. System.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" );
3.
4. // Initialize Gecko Driver using Desired Capabilities Class
5. DesiredCapabilities capabilities = DesiredCapabilities.firefox();
6. capabilities.setCapability("marionette",true);
7. WebDriver driver= new FirefoxDriver(capabilities);

• After that we’d like to write down the code which can automate our second test scenario (navigate to the specified URL)

Here is that the sample code to navigate to the specified URL:

1. // Launch Website
2. driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");

The complete code till now will look something like this:

1. import org.openqa.selenium.WebDriver;
2. import org.openqa.selenium.firefox.FirefoxDriver;
3. import org.openqa.selenium.remote.DesiredCapabilities;
4.
5. public class alert_test {
6.
7. public static void main(String[] args) {
8.
9. // System Property for Gecko Driver
10. System.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" );
11.
12. // Initialize Gecko Driver using Desired Capabilities Class
13. DesiredCapabilities capabilities = DesiredCapabilities.firefox();
14. capabilities.setCapability("marionette",true);
15. WebDriver driver= new FirefoxDriver(capabilities);
16.
17.
18. // Launch Website
19. driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");
20.
21. }
22.
23. }

Step4. Now, we’ll attempt to locate the “Generate Alert Box” and “Generate Confirm Box” so as to perform alert handling operation. As we all know that locating a component involves inspection of its HTML codes.

Follow the steps given below to locate the menu on the sample website .
• Open URL: https://www.testandquiz.com/selenium/testing.html
• Right click on the “Generate Alert Box” button and choose Inspect Element.

hand 3
Generate Alert Box

• It will launch a window containing all the precise codes involved within the development of the “Generate Alert Box” button.

hand 4
window

• Take a note of its link text i.e. “Generate Alert Box”

hand 5
Generate Alert Box

Similarly, we’ll inspect the “Generate Confirm box” button.

hand 6
Inspect

• Take a note of its link text i.e. “Generate Confirm Box”

hand 7
Generate Confirm Box

Step5.
To automate our third and fourth test scenario, we’d like to write down the code which click and accept the Generate Alert box also as click and accept the Generate Confirm box.

Given below is that the code snippet to automate our third and fourth test scenario.

1. //Handling alert boxes
2. //Click on generate alert button
3. driver.findElement(By.linkText("Generate Alert Box")).click();
4.
5. //Using Alert class to first switch to or focus to the alert box
6. Alert alert = driver.switchTo().alert();
7.
8. //Using accept() method to accep the alert box
9. alert.accept();
10.
11. //Handling confirm box
12. //Click on Generate Confirm Box
13. driver.findElement(By.linkText("Generate Confirm Box")).click();
14.
15.
16. Alert confirmBox = driver.switchTo().alert();
17.
18. //Using dismiss() command to dismiss the confirm box
19. //Similarly accept are often wont to accept the confirm box
20. confirmBox.dismiss();
Thus, our final test script will look something like this:
1. import org.openqa.selenium.By;
2. import org.openqa.selenium.WebDriver;
3. import org.openqa.selenium.firefox.FirefoxDriver;
4. import org.openqa.selenium.remote.DesiredCapabilities;
5. import org.openqa.selenium.Alert;
6. public class alert_test {
7.
8. public static void main(String[] args) {
9.
10. // System Property for Gecko Driver
11. System.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" );
12.
13. // Initialize Gecko Driver using Desired Capabilities Class
14. DesiredCapabilities capabilities = DesiredCapabilities.firefox();
15. capabilities.setCapability("marionette",true);
16. WebDriver driver= new FirefoxDriver(capabilities);
17.
18.
19. // Launch Website
20. driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");
21.
22. //Handling alert boxes
23. //Click on generate alert button
24. driver.findElement(By.linkText("Generate Alert Box")).click();
25.
26. //Using Alert class to first switch to or focus to the alert box
27. Alert alert = (Alert) driver.switchTo().alert();
28.
29. //Using accept() method to simply accept the alert box
30. alert.accept();
31.
32. //Handling confirm box
33. //Click on Generate Confirm Box
34. driver.findElement(By.linkText("Generate Confirm Box")).click();
35.
36.
37. Alert confirmBox = (Alert) driver.switchTo().alert();
38.
39. //Using dismiss() command to dismiss the confirm box
40. //Similarly accept are often wont to accept the confirm box
41. ((Alert) confirmBox).dismiss();
42.
43.
44.
45. }
46.
47. }

Upon execution, the above test script will launch the Firefox browser and automate all the test scenarios.

So, this brings us to the end of blog. This Tecklearn ‘How to Handle Alerts in Selenium WebDriver ’ blog helps you with commonly asked questions if you are looking out for a job in Selenium and Automation Testing. If you wish to learn Selenium and build a career in Automation Testing domain, then check out our interactive, Selenium Certification Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Selenium Certification Training

Selenium Certification Training

About the Course

Tecklearn’s Selenium Certification Training enables you to master the complete Selenium suite. The Selenium Training is designed to train developers and manual testers to learn how to automate web applications with a robust framework, and integrate it within the DevOps processes of an organization. This Selenium Certification Training will also help you master important concepts such as TestNG, Selenium IDE, Selenium Grid, Selenium WebDriver, etc. Get hands-on experience on widely used automation frameworks such as Data-Driven Framework, Keyword-Driven Framework, Hybrid Framework, and Behavior Driven Development (BDD) Framework. Throughout this online Instructor-led Selenium Certification Training, you will be working on real-life industry use cases.

Why Should you take Selenium Certification Training?

• The average salary of a Selenium Test Automation Engineer is $94k per year – Indeed.com.
• Automation Testing Market is expected to grow at a Compound Annual Growth Rate (CAGR) of 18.0% in the next three years.
• Global software testing market to reach $50 billion by 2020 – NASSCOM. Selenium tool supports more browsers and languages than any other testing tool.

What you will Learn in this Course?

Getting started with Selenium

• Introduction to Selenium testing
• Significance of automation testing
• Comparison of Manual and Automation Testing
• Installation of Java JDK, JRE and Eclipse

Setting the environment in Eclipse for Selenium

• Java Introduction
• Creating a Java function and executing
• Concepts of Java
• Properties File
• Reading Data from Excel File
• Database Connection
• Hands On

Advantages of Selenium automation testing

• Selenium Features
• Concept of Selenium Integrated Development Environment
• Understanding of the Selenium IDE features
• Addition of Script assertions and general commands
• Deploying the first Selenium Script
• Sample project IDE
• Recording Selenium test case
• Hands On

Selenium Web driver Automation

• Architecture of Selenium Web Driver
• Download and installation
• Creating a Java function using Selenium and execution
• Hands On

Deploying Web Drivers for scripting

• Getting the HTML source of Web Element
• Table and Form Elements
• Firebug extension and Fire Path installation
• Advance User Interactions and Cross Browser Testing
• Hands On

Deep dive into Selenium Web Driver

• Action Commands
• Web Table / Date Picker
• How to Implement Switching Commands in WebDriver
• Alerts
• Frames
• Hands On

Switching Operations in WebDriver using Window

• Selenium Webdriver Wait
• Implicit wait, Explicit wait
• Deploying searching elements using the link text, name, using XPath
• Calendar
• Hands On

Introduction to TestNG Framework

• Introduction to TestNG
• Advantages of TestNG
• Installing TestNG on Eclipse
• Rules to write TestNG
• TestNG Features
• Annotations
• Grouping
• Sequencing: Prioritization and Dependency
• Enable/Disable a test case
• Parameterization: Using Xml file and DataProvider
• Parallel Testing & Cross Browser Testing
• TestNG Report: HTML Report, Console Report, XML Report

JUnit Operations and Test Framework

• Annotations, Methods in JUnit
• Junit Test Suites, ANT Build and JUNIT reporting
• Types of Test Automation Framework
• Module Based Testing Framework
• Data Driven Testing Framework
• Keyword Driven Testing Framework
• Hybrid Driven Testing Framework
• How to implement Testing Framework in Project

Object Repository

• Understanding of Object Repository
• Learning sample scripts using object repository
• Page Object Modelling
• Page Factory

JavaScript Functions

• Autosuggestion
• Headless Browser
• Sikuli
• XPath

Got a question for us? Please mention it in the comments section and we will get back to you.

0 responses on "How to Handle Alerts in Selenium WebDriver"

Leave a Message

Your email address will not be published. Required fields are marked *