DEV Community

Cover image for Selenium C# Tutorial: Handling Alert Windows
himanshuseth004 for LambdaTest

Posted on • Edited on • Originally published at lambdatest.com

Selenium C# Tutorial: Handling Alert Windows

Alert windows are pop-up windows that are extensively used across different types of websites or web applications. Alert window alerts the user and expects an action from the user post that alert.

Alerts are also shown when the user is seeking permission to perform a certain operation. Alerts are also used to issue warnings to the end-user of the web product. Alerts are triggered via the alert() method in JavaScript. In this Selenium C# tutorial, we look at using Selenium test automation for handling alert in Selenium C#.

Types Of Alerts In Selenium C

The different types of alerts in Selenium C# are:

  • Simple Alert – This type of alert in Selenium C# is used for displaying warning or certain information on the screen.
  • Confirmation Alert – This type of alert in Selenium C# seeks permission from the user to continue performing the intended operation. The preferred options could be ‘Yes’ (Continue) or ‘No’ (Cancel).
  • Prompt Alert – This alert in Selenium C# expects the user to enter some information into the text box.

One major difference between alert window and a regular window is that alert window is blocking in nature i.e. the user needs to perform some operation on the alert window before proceeding further on the website (or web application).

Operations On Alerts In Selenium C

The operation being performed on an alert window depends on the type of alert being used. The common operations on alert windows are:

  • Dismiss – It is used to dismiss (i.e. cancel) the alert.
  • Accept – It is used to accept the alert in Selenium C#.
  • Text – It is used to read the message from the alert window
  • SendKeys – It is used to enter some textual information in the text box provided in the alert window

Shown below is an example of alert window in Selenium C#

Selenium-c#

For performing valid operations on the alert in Selenium C#, a SwitchTo() operation has to be performed to switch to the alert window. Once the current window is the alert window, appropriate operation i.e. accept, dismiss, etc. can be performed on the alert.

switch.to

In the further section of the Selenium C# tutorial, we look at Selenium C# examples that use the NUnit test framework for demonstrating usage of alert windows including authentication alerts. In case you haven’t set up visual studio, you can read our article to get a clearer understanding about it.

Handling Different Alert Types Using Selenium C

This part of the alerts in Selenium C# tutorial caters to handling alert types such as simple, confirmation, and prompt alerts. As the changes in implementation for handling these alerts are not significant hence, we have combined the three in a single source file.

The test URL which contains these different alert types are http://the-internet.herokuapp.com/javascript_alerts. Commonly used NUnit annotations such as [SetUp], [Test], [Order], and [TearDown] are used in the implementation. In one of the earlier blogs, we covered the NUnit framework in great detail.

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using SeleniumExtras.WaitHelpers;
using System;

namespace Selenium_ExplicitWait_Demo
{
    class Selenium_ExplicitWait_Demo
    {
        String test_url = "http://the-internet.herokuapp.com/javascript_alerts";

        IWebDriver driver;

        [SetUp]
        public void start_Browser()
        {
            // Local Selenium WebDriver
            driver = new ChromeDriver();
            driver.Manage().Window.Maximize();
        }

        [Test, Order(1)]
        public void test_alert()
        {
            String button_xpath = "//button[.='Click for JS Alert']";
            var expectedAlertText = "I am a JS Alert";

            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            driver.Url = test_url;

            /* IWebElement alertButton = driver.FindElement(By.XPath(button_xpath)); */

            IWebElement alertButton = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.XPath(button_xpath)));
            alertButton.Click();

            var alert_win = driver.SwitchTo().Alert();
            Assert.AreEqual(expectedAlertText, alert_win.Text);

            alert_win.Accept();

            /* IWebElement clickResult = driver.FindElement(By.Id("result")); */

            var clickResult = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.Id("result")));

            Console.WriteLine(clickResult.Text);

            if (clickResult.Text == "You successfuly clicked an alert")
            {
                Console.WriteLine("Alert Test Successful");
            }
        }

        [Test, Order(2)]
        public void test_confirm()
        {
            String button_css_selector = "button[onclick='jsConfirm()']";
            var expectedAlertText = "I am a JS Confirm";

            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            driver.Url = test_url;

            IWebElement confirmButton = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(button_css_selector)));

            confirmButton.Click();

            var confirm_win = driver.SwitchTo().Alert();
            confirm_win.Accept();

            IWebElement clickResult = driver.FindElement(By.Id("result"));
            Console.WriteLine(clickResult.Text);

            if (clickResult.Text == "You clicked: Ok")
            {
                Console.WriteLine("Confirm Test Successful");
            }
        }

        [Test, Order(3)]
        public void test_dismiss()
        {
            String button_css_selector = "button[onclick='jsConfirm()']";
            var expectedAlertText = "I am a JS Confirm";

            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            driver.Url = test_url;

            IWebElement confirmButton = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(button_css_selector)));

            confirmButton.Click();

            var confirm_win = driver.SwitchTo().Alert();
            confirm_win.Dismiss();

            IWebElement clickResult = driver.FindElement(By.Id("result"));
            Console.WriteLine(clickResult.Text);

            if (clickResult.Text == "You clicked: Cancel")
            {
                Console.WriteLine("Dismiss Test Successful");
            }
        }

        [Test, Order(4)]
        public void test_sendalert_text()
        {
            String button_css_selector = "button[onclick='jsPrompt()']";
            var expectedAlertText = "I am a JS prompt";

            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
            driver.Url = test_url;

            IWebElement confirmButton = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(button_css_selector)));
            confirmButton.Click();

            var alert_win = driver.SwitchTo().Alert();
            alert_win.SendKeys("This is a test alert message");
            alert_win.Accept();

            IWebElement clickResult = driver.FindElement(By.Id("result"));
            Console.WriteLine(clickResult.Text);

            if (clickResult.Text == "You entered: This is a test alert message")
            {
                Console.WriteLine("Send Text Alert Test Successful");
            }
        }

        [TearDown]
        public void close_Browser()
        {
            driver.Quit();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

There are four test cases that show the handling of alert operations such as accept, dismiss, and SendKeys.

Need a great solution for Safari browser testing on Windows? Forget about emulators or simulators — use real online Safari browser for Windows.

Test Case 1 – test_alert()

An explicit wait of 10 seconds is added to ensure that the alert button (I am a JS Alert) is loaded on the page.

JS-alert

Once the button is loaded, a Click() operation is performed to load the alert window.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
driver.Url = test_url;

/* IWebElement alertButton = driver.FindElement(By.XPath(button_xpath)); */
IWebElement alertButton = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.XPath(button_xpath)));
alertButton.Click();
Enter fullscreen mode Exit fullscreen mode

Once the alert window is loaded, the SwitchTo() command is used to switch the context to the alert window. The alert is accepted using the accept() method.

var alert_win = driver.SwitchTo().Alert();
Assert.AreEqual(expectedAlertText, alert_win.Text);
alert_win.Accept();
Enter fullscreen mode Exit fullscreen mode

The end result which appears in the web element with id=result is compared with expected resultant string.

var clickResult = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.Id("result")));

Console.WriteLine(clickResult.Text);

if (clickResult.Text == "You successfully clicked an alert")
{
    Console.WriteLine("Alert Test Successful");
}
Enter fullscreen mode Exit fullscreen mode

Test Case 2 – test_confirm()

The alert window pops up on clicking the button ‘Click for JS Confirm’. Like the previous test case, an explicit wait is performed so that the button is loaded.

JS-conformation

Once the alert window ‘I am a JS Confirm’ is loaded, accept() method is used to accept the alert operation.

IWebElement confirmButton = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(button_css_selector)));

confirmButton.Click();

var confirm_win = driver.SwitchTo().Alert();
confirm_win.Accept();

IWebElement clickResult = driver.FindElement(By.Id("result"));
Console.WriteLine(clickResult.Text);
Enter fullscreen mode Exit fullscreen mode

Test Case 3 – test_dimiss()

The alert window used in this test case is the same as the one is test case 2 (test_confirm). The only difference is that instead of the accept() method for alert in Selenium C#, the dismiss method is used to dismiss the alert window.

JS-confirm

Once we switch to the alert window, the alert is dismissed using the dismiss method. The resultant text is ‘You clicked: Cancel’.

IWebElement confirmButton = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementExists(By.CssSelector(button_css_selector)));

confirmButton.Click();

var confirm_win = driver.SwitchTo().Alert();
confirm_win.Dismiss();
Enter fullscreen mode Exit fullscreen mode

Test Case 4 – test_sendalert_text()

The button with CssSelector = button[onclick='jsPrompt()'] is located using the Inspect tool in Chrome. Once the button is located, a click operation is performed to trigger the alert.

sendalrts

Once the alert window is opened, the SendKeys() method for alert in Selenium C# is used to populate the alert text box with the text ‘This is a test alert message’. Once the text is entered, accept() method is used to accept the alert message.

var alert_win = driver.SwitchTo().Alert();
alert_win.SendKeys("This is a test alert message");
alert_win.Accept();
Enter fullscreen mode Exit fullscreen mode

javascript-alert

Here is the output snapshot from Visual Studio 2019. As shown below, all the four tests have passed.

Output

Result

In this article, we take a look at some aspects of simulation and discuss some ways through which we can use ios Simulator for PC.

Handling Authentication Alerts In Selenium C

Authentication alerts (or pop-ups) are used in websites when the user needs to have valid credentials to access the features of the site. The credentials would normally comprise of a valid user-name and password.

Here is an example of an authentication where you need to enter valid credentials to access the website.

authantication

The preferred way of handling authentication alerts in Selenium C# is by passing user-credentials in the URL. After appending user-name and password to the URL, the final URL will be http://[user-name]:[password]@website.com

The site used for demonstration is https://the-internet.herokuapp.com/basic_auth and its credentials are username – admin & password – admin. Hence, the URL on which we perform Selenium test automation is: http://admin:admin@the-internet.herokuapp.com/basic_auth

using NUnit.Framework;
using System;
using System.Collections.ObjectModel;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using SeleniumExtras.WaitHelpers;

namespace Selenium_Window_Demo_2
{
    class Selenium_Window_Demo_2
    {
        IWebDriver driver;

        public String getCurrentWindowTitle()
        {
            String windowTitle = driver.Title;
            return windowTitle;
        }

        [SetUp]
        public void start_Browser()
        {
            /* Local Selenium WebDriver */
            driver = new ChromeDriver();
            driver.Manage().Window.Maximize();
        }

      [Test]        
      public void test_window_ops()
        {
            /* Link format is http://user-name:password@website.com */
            String test_url_1 = "http://admin:admin@the-internet.herokuapp.com/basic_auth";
            IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

            driver.Url = test_url_1;

            /* Not a good practice to use Thread.Sleep as it is a blocking call */
            /* Used here for demonstration */
            System.Threading.Thread.Sleep(4000);

            IWebElement Message_elem = driver.FindElement(By.CssSelector("p"));
            String Message = Message_elem.Text;

            System.Threading.Thread.Sleep(2000);

            Console.WriteLine("Output message is: " + Message);
        }

        [TearDown]
        public void close_Browser()
        {
            driver.Quit();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

As we have passed valid credentials in the URL, login is successful.

String test_url_1 = "http://admin:admin@the-internet.herokuapp.com/basic_auth";
driver.Url = test_url_1;
Enter fullscreen mode Exit fullscreen mode

The output message on the screen is compared with the expected message.

IWebElement Message_elem = driver.FindElement(By.CssSelector("p"));
String Message = Message_elem.Text;
Console.WriteLine("Output message is: " + Message);
Enter fullscreen mode Exit fullscreen mode

Here is the execution snapshot from Visual Studio and Chrome browser

visualstudio-chrome

basic-auth

Conclusion

Alert windows are commonly used in websites for warning or information users present on the site. Alerts are normally triggered on the click of a button. Accept, dismiss, and SendKeys are the widely used methods for handling alert in Selenium C#. Selenium test automation for websites that pop-up authentication alerts is also performed using the same fundamentals as normal alert windows. If you like you can also visit our Previous Selenium C# tutorial on setting up visual studio, implicit waits, explicit & fluent wait.

Happy Testing! Do leave your feedback & suggestions in the comments section so that we can co-learn and contribute to jointly solving Selenium test automation problems!

Top comments (0)