http://www.softwaretestinghelp.com/handle-alerts-popups-selenium-webdriver-selenium-tutorial-16/
Efficient Ways to Handle Windows and Web based Alerts/Popups in Selenium WebDriver:
In the previous tutorial, we focused our discussion on different types of waits provided by the WebDriver. We also discussed about various types of navigation options available in WebDriver.
Moving ahead in the Selenium WebDriver Tutorials, we will discuss about different types of alerts available while testing web applications and their handling strategies.
There are two types of alerts that we would be focusing on majorly:
- Windows based alert pop ups
- Web based alert pop ups
As we know that handling windows based pop ups is beyond WebDriver’s capabilities, thus we would exercise some third party utilities to handle window pop ups.
Handling pop up is one of the most challenging piece of work to automate while testing web applications. Owing to the diversity in types of pop ups complexes the situation even more.
What is Alert box/ Pop up box/ confirmation Box/ Prompt/ Authentication Box?
It is nothing but a small box that appears on the display screen to give you some kind of information or to warn you about a potentially damaging operation or it may even ask you for the permissions for the operation.
Example: Let us consider a real life example for a better understanding; Let us assume that we uploaded a photograph on any of these popular social networking sites. Later on, i wish to delete the uploaded photograph. So in order to delete, i clicked on the delete button. As soon as I click on the delete button, the system warns me against my action, prompting – Do you really want to delete the file? So now we have an option to either accept this alert or reject it.
So ahead in the session, let’s see how do we reject or accept the alerts depending on their types. Starting with the web based pop ups.
Web Based Popups
Let us see how do we handle them using WebDriver.
Handling web based pop-up box
WebDriver offers the users with a very efficient way to handle these pop ups using Alert interface.
There are the four methods that we would be using along with the Alert interface.
1) void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.
2) void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
3) String getText() – The getText() method returns the text displayed on the alert box.
4) void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
Let us move ahead and look at the actual implementation.
Explanation of Application under Test
We have designed a web page in a way to include a few fundamental types of web elements. This is the same application we introduced while discussing Select class earlier in this series.
-
Hyperlink: The two hyperlinks namely “Google” and “abodeQA” have been provided that re-directs the user to “http://www.google.com/” and “http://www.abodeqa.com/” respectively on the click event.
-
Dropdown: The three hyperlinks have been created for selecting colors, fruits and animals with a value set to default.
-
Button: A “try it” button has been created to show up the pop up box having OK and Cancel buttons upon click event.
(Click on image to view enlarged)
Subsequent is the HTML code used to create the above mentioned webpage:
3 |
< head >< title > Testing Select Class </ title >
|
8 |
< a href = "https://www.google.com/" >Google</ a >
|
11 |
< a href = "http://abodeqa.wordpress.com/" >abodeQA</ a >
|
15 |
< div class = "header_spacer" ></ div >
|
17 |
< div id = "content" style = "padding-left: 185px;" >
|
18 |
< table id = "selectTable" >
|
23 |
< select id = "SelectID_One" >
|
24 |
< option value = "redvalue" >Red</ option >
|
25 |
< option value = "greenvalue" >Green</ option >
|
26 |
< option value = "yellowvalue" >Yellow</ option >
|
27 |
< option value = "greyvalue" >Grey</ option >
|
33 |
< select id = "SelectID_Two" >
|
34 |
< option value = "applevalue" >Apple</ option >
|
35 |
< option value = "orangevalue" >Orange</ option >
|
36 |
< option value = "mangovalue" >Mango</ option >
|
37 |
< option value = "limevalue" >Lime</ option >
|
43 |
< select id = "SelectID_Three" >
|
44 |
< option value = "selectValue" >Select</ option >
|
45 |
< option value = "elephantvalue" >Elephant</ option >
|
46 |
< option value = "mousevalue" >Mouse</ option >
|
47 |
< option value = "dogvalue" >Dog</ option >
|
58 |
< p >Click the button to display a confirm box.</ p >
|
59 |
< button onclick = "myFunction()" >Try it</ button >
|
64 |
confirm("Press a button!"); |
Scenario to be automated
- Launch the web browser and open the webpage
- Click on the “Try it” button
- Accept the alert
- Click on the “Try it” button again
- Reject the alert
WebDriver Code using Select Class
Please take a note that for script creation, we would be using “Learning_Selenium” project created in the former tutorial.
Step 1: Create a new java class named as “DemoWebAlert” under the “Learning_Selenium” project.
Step 2: Copy and paste the below code in the “DemoWebAlert.java” class.
Below is the test script that is equivalent to the above mentioned scenario.
1 |
import org.junit.After;
|
2 |
import org.junit.Before;
|
4 |
import org.openqa.selenium.Alert;
|
5 |
import org.openqa.selenium.By;
|
6 |
import org.openqa.selenium.WebDriver;
|
7 |
import org.openqa.selenium.firefox.FirefoxDriver;
|
13 |
public class DemoWebAlert {
|
18 |
public DemoWebAlert() {
|
22 |
* Set up browser settings and open the application
|
27 |
driver= new FirefoxDriver();
|
29 |
driver.get( "file:///F:/Work/Selenium/Testing-Presentation/DemoWebPopup.htm" );
|
30 |
driver.manage().window().maximize();
|
34 |
* Test to check Select functionality
|
35 |
* @throws InterruptedException
|
39 |
public void testWebAlert() throws InterruptedException {
|
41 |
driver.findElement(By.xpath( "//button[contains(text(),'Try it')]" )).click();
|
45 |
Alert alert = driver.switchTo().alert();
|
49 |
driver.findElement(By.xpath( "//button[contains(text(),'Try it')]" )).click();
|
53 |
driver.switchTo().alert().dismiss();
|
56 |
driver.findElement(By.xpath( "//button[contains(text(),'Try it')]" )).click();
|
60 |
System.out.println(driver.switchTo().alert().getText());
|
61 |
driver.switchTo().alert().accept();
|
65 |
* Tear down the setup after test completes
|
69 |
public void tearDown() {
|
Code Walk-through
Import Statements
Import org.openqa.selenium.Alert – Import this package prior to the script creation The package references to the Alert class which is required to handle the web based alerts in WebDriver.
Object Creation for Alert class
Alert alert = driver.switchTo().alert();
We create a reference variable for Alert class and references it to the alert.
Switch to Alert
Driver.switchTo().alert();
The above command is used to switch the control to the recently generated pop up window.
Accept the Alert
alert.accept();
The above command accepts the alert thereby clicking on the Ok button.
Reject the Alert
alert.dismiss();
The above command closes the alert thereby clicking on the Cancel button and hence the operation should not proceed.
Window Based Pop Ups
At times while automating, we get some scenarios, where we need to handle pop ups generated by windows like a print pop up or a browsing window while uploading a file.
Handling these pop-ups have always been a little tricky as we know Selenium is an automation testing tool which supports only web application testing, that means, it doesn’t support windows based applications and window alert is one of them. However Selenium alone can’t help the situation but along with some third party intervention, this problem can be overcome.
There are several third party tools available for handling window based pop-ups along with the selenium.
So now let’s handle a window based pop up using Robot class.
Robot class is a java based utility which emulates the keyboard and mouse actions.
Before moving ahead, let us take a moment to have a look at the application under test (AUT).
Explanation of Application under Test
As an application under test, we would be using “gmail.com”. I believe the application doesn’t require any more introductions.
Scenario to be automated
- Launch the web browser and open the application – “gmail.com”
- Enter valid username and password
- Click on the sign in button
- Click on the a compose button
- Click on the attach icon
- Select the files to be uploaded with the window based pop up.
WebDriver Code using Robot Class
Please take a note that for script creation, we would be using “Learning_Selenium” project created in the former tutorial.
Step 1: Create a new java class named as “DemoWindowAlert” under the “Learning_Selenium” project.
Step 2: Copy and paste the below code in the “DemoWindowAlert.java” class.
Below is the test script that is equivalent to the above mentioned scenario.
1 |
import java.awt.Robot;</pre>
|
2 |
import java.awt.event.KeyEvent;
|
3 |
import org.junit.After;
|
4 |
import org.junit.Before;
|
6 |
import org.openqa.selenium.By;
|
7 |
import org.openqa.selenium.WebDriver;
|
8 |
import org.openqa.selenium.firefox.FirefoxDriver;
|
10 |
public class DemoWindowAlert {
|
16 |
driver= new FirefoxDriver();
|
17 |
driver.get( "https://gmail.com" );
|
18 |
driver.manage().window().maximize(); |
22 |
public void testWindowAlert() throws Exception{
|
25 |
driver.findElement(By.id( "Email" )).sendKeys( "TestSelenium1607@gmail.com" );
|
28 |
driver.findElement(By.id( "Passwd" )).sendKeys( "TestSelenium" );
|
31 |
driver.findElement(By.id( "signIn" )).click();
|
35 |
driver.findElement(By.xpath( "//div[@class='z0']//div[contains(text(),'COMPOSE')]" )).click();
|
38 |
driver.findElement(By.xpath( "//div[contains(@command,'Files')]//div[contains(@class,'aaA')]" )).click();
|
41 |
Robot rb = new Robot();
|
44 |
rb.keyPress(KeyEvent.VK_D); |
45 |
rb.keyRelease(KeyEvent.VK_D); |
48 |
rb.keyPress(KeyEvent.VK_SHIFT); |
49 |
rb.keyPress(KeyEvent.VK_SEMICOLON); |
50 |
rb.keyRelease(KeyEvent.VK_SEMICOLON); |
51 |
rb.keyRelease(KeyEvent.VK_SHIFT); |
53 |
rb.keyPress(KeyEvent.VK_BACK_SLASH); |
54 |
rb.keyRelease(KeyEvent.VK_BACK_SLASH); |
57 |
rb.keyPress(KeyEvent.VK_P); |
58 |
rb.keyRelease(KeyEvent.VK_P); |
60 |
rb.keyPress(KeyEvent.VK_I); |
61 |
rb.keyRelease(KeyEvent.VK_I); |
63 |
rb.keyPress(KeyEvent.VK_C); |
64 |
rb.keyRelease(KeyEvent.VK_C); |
67 |
rb.keyPress(KeyEvent.VK_ENTER); |
68 |
rb.keyRelease(KeyEvent.VK_ENTER); |
73 |
public void tearDown()
|
Code Walk-through
Import Statements
import java.awt.Robot – Import this package prior to the script creation The package references to the Robot class in java which is required simulate keyboard and mouse events.
import java.awt.event.KeyEvent – The package allows the user to use keyPress and keyRelease events of keyboard.
Object Creation for Robot class
Robot rb =new Robot();
We create a reference variable for Robot class and instantiate it.
KeyPress and KeyRelease Events
rb.keyPress(KeyEvent.VK_D);
rb.keyRelease(KeyEvent.VK_D);
The keyPress and keyRelease methods simulate the user pressing and releasing a certain key on the keyboard respectively.
Conclusion
In this tutorial, we tried to make you acquainted with the WebDriver’s Alert class that is used to handle web based pop ups. We also briefed you about the Robot class that can be used to populate the value in the window based alert with the help of keyPress and keyRelease events.
Article summary:
- Alerts are a small box that appears on the display screen to give you some kind of information or to warn you about a potentially damaging operation or it may even ask you for the permissions for the operation.
-
There are popularly two types of alerts–
- Windows based alert pop ups
- Web based alert pop ups
- Prior to the actual scripting, we need to import a package to be able to create a WebDriver script for handling a dropdown and making the Select class accessible.
- WebDriver offers the users with a very efficient way to handle these pop ups using Alert interface.
-
void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.
-
void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
- String getText() – The getText() method returns the text displayed on the alert box.
-
void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
-
Handling window based pop-ups have always been a little tricky as we know Selenium is an automation testing tool which supports only web application testing, that means, it doesn’t support windows based applications and window alert is one of them.
-
Robot class is a java based utility which emulates the keyboard and mouse actions and can be effectively used to handling window based pop up with the help of keyboard events.
- The keyPress and keyRelease methods simulate the user pressing and releasing a certain key on the keyboard respectively.
Next Tutorial #17: In the upcoming tutorial, we would discuss about the various other commonly used WebDriver commands. We would shed light on topics like exception handling and iframe handling. We would also discuss about the get commands provided in WebDriver.
We would explain these topics with quick examples in order to make them understandable for the readers to exercise these concepts in their day to day scripting.
Note for the Readers: Till then, stay tuned and automate the web pages having web based and window based pop ups using WebDriver utility – “Alert class” and Java utility – “Robot Class”
相关推荐
Over 90 recipes to help you build and run automated tests for your web applications with Selenium WebDriver About This Book Learn to leverage the power of Selenium WebDriver with simple examples that...
E/WifiStateMachine( 1670): Failed to set primary device type 10-0050F204-5 D/CommandListener( 1249): Setting iface cfg D/CommandListener( 1249): Trying to bring up p2p0 D/WifiMonitor( 1670): start...
v.displayalerts:=false; v.quit; exit; end; application.Restore; application.BringToFront; end; procedure TForm1.Button2Click(Sender: TObject); begin if opendialog1.Execute then begin try V:=...
基于jQuery的弹出警告对话框美化插件(警告,确认和提示) 这个Jquery插件的目的是...详细出处参考:file:///F:/闫洪明/新建文件夹/1alerts/基于jQuery的弹出警告对话框美化插件(警告,确认和提示)_jquery_脚本之家.mht
淘汰赛警报 显示引导程序和类似引导程序警报的组件。 入门 从凉亭安装: ... 'ko-alerts' : 'bower_components/ko-alerts' } } ) ; require ( [ 'knockout' ] , function ( ko ) { ko . components . regi
加密毫升警报 从获取警报安装 NPM 安装: npm install --global crypto-ml-alerts 可执行文件: crypto-ml-alerts 版本该软件包发布了以下版本: crypto-ml-alerts别名crypto-ml-alerts/source/index.js crypto-ml-...
语言:Deutsch,English 简单概述Chrome中的行李箱2警报。 *功能*: - 现代设计 - 显示... https://github.com/kurtextrem/ps2alerts/releases/tag/1.1. 代码存储库:https://github.com/kurtextrem/ps2alerts Reddit:...
https://github.com/kurtextrem/PS2Alerts/releases/tag/1.1.1代码存储库:https://github.com/kurtextrem/PS2Alerts Reddit:http://de.reddit.com/r/Planetside/comments / 1w1oxt / is_there_need_for_a_chrome_...
the provided filtering and view building tools, and how to manage alerts received from Netcool/OMNIbus. It also provides information on using the Lightweight Event List (LEL) and the tableview. • ...
--Facility is not officially supported in GELF anymore, but you can use staticFields to do the same thing--> <key>tag</key> <value>business-server</value> </staticField> </layout> </encoder>...
在终端/命令提示符中运行: git clone https://github.com/manoj-mone/alerts-list-ntnx.gitcd alerts-list-ntnx/python3 -m pip install virtualenvpython3 -m virtualenv venv在UNIX系统中: source venv/bin/...
puppet consul_alerts目录概述该模块可以将 consul_alerts 工具包安装到您的机器上。 它支持: Debian Wheezy Ubuntu 精确/可信CentOS/RHEL 5 或 6 关于 consul-alerts 的更多信息在他们的 github repo 上: : 模块...
excel->setProperty("DisplayAlerts", false); // 不显示任何警告信息。如果为true, 那么关闭时会出现类似"文件已修改,是否保存"的提示 // step2: 打开工作簿 QAxObject* workbooks = excel->querySubObject(...
NULL 博文链接:https://wabaper.iteye.com/blog/1532909
greet` function from Rust to JavaScript, that alerts a // hello message. #[wasm_bindgen] pub fn greet (name: & str ) { alert ( & format! ( "Hello, {}!" , name)); } 通过ECMAScript模块使用从...
资源分类:Python库 所属语言:Python 资源全名:google_alerts-0.2.7-py2-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
Tatter \ Alerts 轻型用户警报CodeIgniter 4快速开始运行: > composer require tatter/alerts 加载助手: helper('alerts'); 设置警报: alert('success', "You did it!") 添加头标签(可选): <?= ...
资源分类:Python库 所属语言:Python 资源全名:ampel_alerts-0.8.1a3-py3-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
greet` function from Rust to JavaScript, that alerts a// hello message. #[wasm_bindgen]pubfngreet (name:&str ) {alert (&format! ("Hello, {}!" , name)); }将 JavaScript 中导出的 Rust ...
unity游戏对话系统Dialogue System for Unity 2.0.2 Requires Unity 5.3.6 or higher. Version 1.x to 2.x Upgrade ...Barks and alerts Cutscenes (audio, animation, etc.) Quick Time Events (QTEs) Quest system