Latest post from this blog

How to Manage Test Execution Across Different Browsers and Environments (QA, UAT, Staging)

In real-time automation projects, test execution is never limited to a single browser or a single environment . Applications must be validated across multiple browsers (Chrome, Firefox, Edge) and multiple environments such as QA, UAT, and Staging before going live. A well-designed Selenium + Java + Cucumber automation framework should allow testers to switch browsers and environments easily without changing test scripts . This blog explains how to manage test execution efficiently across different browsers and environments using best practices followed in real projects. Why Multi-Browser and Multi-Environment Testing Is Important Different users use different browsers QA, UAT, and Staging environments have different configurations Bugs may appear only in specific environments or browsers Same test cases must be validated everywhere before production release Common Challenges Testers Face Hardcoded browser names and URLs Maintaining separate test scripts for each environment Browse...

Handling Alerts and Pop-Ups in Selenium WebDriver

Introduction 
In Selenium, alerts are pop-up messages that show important information or ask for user confirmation. They can be used to display information, confirm actions, or prompt the user for input. Selenium provides methods to handle these alerts during automated testing.

What Are Alerts
In Selenium, alerts are pop-up messages displayed on the browser window. We'll focus on two main types of alerts:

1.Web-based Alerts: Handled directly by Selenium WebDriver.

2.Windows-based Alerts: System-level pop-ups requiring external tools or libraries for interaction.

Types of Web-based alert in Selenium
1.Alert: Displays a simple message and an "OK" button.

2.Confirm: This type of alert is typically used to confirm certain actions.

For Example, when entering personal details in a web application, an alert may appear if you attempt to navigate away from the page without submitting the form. It will ask, "Do you want to save changes?" with options like "Yes" or "No."

3.Prompt: This Prompt Alert requests input from the user, and Selenium WebDriver can use the sendKeys() method to provide the required text.

For Example, on a Facebook login page, if the user enters only the email address but leaves the password field empty, a prompt may appear asking the user to provide the missing information.

How to Handle Alerts in Selenium
Selenium provides methods to interact with web-based alerts:

1.dismiss(): This method clicks the 'Cancel' button on an alert box.

 Syntax:
   driver.switchTo().alert().dismiss();
   
2.accept(): This method clicks the 'OK' button on an alert.

Syntax:
   driver.switchTo().alert().accept();

3.getText(): This method retrieves the message displayed in the alert.

Syntax:
   driver.switchTo().alert().getText();

4.sendKeys(String text): This method inputs data into the alert box.

Syntax: driver.switchTo().alert().sendKeys("Text");

Example:
 import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AlertHandlingExample {

    public static void main(String[] args) {
        // Set the path for the ChromeDriver
        System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");

        // Initialize WebDriver
        WebDriver driver = new ChromeDriver();

        try {
            // Open a webpage that triggers an alert
            driver.get("https://example.com/trigger-alert");

            // Wait for the alert to be displayed
            Thread.sleep(2000); // Just for demo purposes, better to use explicit waits

            // Switch to the alert
            Alert alert = driver.switchTo().alert();

            // Example 1: Get the alert message
            String alertMessage = alert.getText();
            System.out.println("Alert message: " + alertMessage);

            // Example 2: Send input to a prompt alert
            alert.sendKeys("This is my input");

            // Example 3: Accept the alert (click 'OK')
            alert.accept();

            // Wait for another alert to appear, for example
            Thread.sleep(2000);

            // Switch to the next alert (if there's another one)
            alert = driver.switchTo().alert();

            // Example 4: Dismiss the alert (click 'Cancel')
            alert.dismiss();
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // Close the browser
            driver.quit();
        }
    }
}

Windows-based alert: When dealing with Windows-based alert pop-ups, Selenium alone can't interact with these system-level dialogs. However, there are various tools and methods available to manage such pop-ups effectively.  Below, we focus on two commonly used methods in automation: AutoIt, Robot Class.

i.Using the Robot Class for Basic Windows Pop-up Handling:
The Robot class in Java simulates keyboard and mouse actions, allowing you to interact with system pop-ups.

Code Example Using Robot Class to Handle File Upload Dialog:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

public class RobotClassExample {
    public static void main(String[] args) throws AWTException {
        // Set up WebDriver and open a website with a file upload field
        System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com/file-upload");

        // Click on the upload button to open the file dialog
        driver.findElement(By.id("uploadButton")).click();

        // Use Robot class to upload a file
        Robot robot = new Robot();
        robot.delay(2000); // Wait for the dialog to open

        // Set the file path in the system clipboard
        StringSelection filePath = new StringSelection("C:\\path\\to\\file.txt");
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(filePath, null);

        // Paste the file path
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);

        // Press Enter to confirm
        robot.keyPress(KeyEvent.VK_ENTER);
        robot.keyRelease(KeyEvent.VK_ENTER);

        // Close the browser
        driver.quit();
    }
}

ii.Using AutoIt to Handle a File Upload Dialog:
AutoIt allows you to interact with system-level dialogs like file upload or download pop-ups in Windows.

Steps:
1.Download and install AutoIt from the official website.
2.Write a script in AutoIt to handle the pop-up.
3.Compile the script into an executable .exe file.
4.Trigger the AutoIt script using Selenium.

AutoIt Script (FileUpload.au3):
ControlFocus("File Upload", "", "Edit1")
ControlSetText("File Upload", "", "Edit1", "C:\\path\\to\\file.txt")
ControlClick("File Upload", "", "Button1")

Example:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AutoItExample {
    public static void main(String[] args) throws IOException {
        System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://example.com/file-upload");

        driver.findElement(By.id("uploadButton")).click();

        Runtime.getRuntime().exec("path_to_autoit_script.exe");

        driver.quit();
    }
}
After saving the script, compile it into an .exe file using AutoIt’s compiler.

iii.Sikuli is excellent for image-based automation, ideal for custom or non-standard pop-ups.

iV.Winium provides a more robust solution for full desktop application automation.

Conclusion
Alerts and pop-ups are critical components of web and desktop applications. Selenium offers robust methods for handling web-based alerts, while tools like Robot Class, AutoIt, and Sikuli fill the gap for system-level interactions. Mastering these techniques will help testers create more reliable and efficient automation scripts.



Comments

Popular posts from this blog

How to Manage Test Execution Across Different Browsers and Environments (QA, UAT, Staging)

Purpose of the StepData Class in Selenium + Java Cucumber Automation Framework

Ensuring Thread Safety in Parallel Test Execution with Selenium, Cucumber, and Java