qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

Selenium2.0功能测试之Alert/Confirm/Prompt的处理

 WebDriver中处理原生JS的 alert confirm 以及prompt是很方便的(虽然现在原生JS的实现方式用的很少了)。具体思路是使用switchTo.alert()方法定位到当前的alert/confirm/prompt(这里注意当前页面只能同时含有一个控件,如果多了会报错的,所以这就需要一一处理了),然后在调用Alert的方法进行操作,Alert提供了以下几个方法:
  getText : 返回alert/confirm/prompt中的文字内容
  accept : 点击确认按钮
  dismiss : 点击取消按钮如果有取消按钮的话
  sendKeys : 向prompt中输入文字    //这个方法在chromedriver中不起作用,IE的话由于家中无Windows没有做demo.
package org.coderinfo.demo;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class AlertDemo {
private static final String URL = "file:///home/moon/Desktop/alert_demo.html";
/**
* @author CoderInfo
*/
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();  //创建一个firefox的 webdriver
driver.get(URL);
driver.manage().window().maximize();
Thread.sleep(1000);
// 点击弹出alert
driver.findElement(By.id("alert")).click();
Thread.sleep(3000);
Alert alert = driver.switchTo().alert(); //捕获alert
alert.accept();  //点击确认按钮
Thread.sleep(3000);  //等待3s
//点击弹出confirm
driver.findElement(By.id("confirm")).click();
Thread.sleep(3000);
Alert confirm = driver.switchTo().alert();  //捕获confirm
String confirmText = confirm.getText(); //获取confirm中的文字信息
System.out.println(confirmText);
confirm.accept();  //confirm 点击确认按钮
//      confirm.dismiss();  //confirm点击取消按钮
Thread.sleep(3000);
//点击弹出prompt
driver.findElement(By.id("prompt")).click();
Thread.sleep(3000);
Alert prompt = driver.switchTo().alert();  //捕获prompt
//      String promptText = prompt.getText(); //获取prompt中的文字信息
//      System.out.println(promptText);
prompt.sendKeys("可能是由于太懒了");  //向prompt中输入内容
Thread.sleep(3000);
prompt.accept();  //prompt 点击确认按钮
//      prompt.dismiss();  //prompt点击取消按钮
Thread.sleep(3000);
driver.quit(); // close webdriver
}
}

 下面是测试页面alert_demo.html源代码
<html>
<head>
<title>Alert</title>
<script type="text/javascript">
function testAlert(){
alert("测试Alert");
}
function testConfirm(){
confirm("你喜欢自动化测试吗?");
}
function testPrompt(){
var content = prompt("你为什么喜欢自动化?");
document.write(content);
}
</script>
</head>
<body>
<h2>Test Alert</h2>
<input type="button" value="alert" onclick="testAlert()" id="alert"/>
<input type="button" value="confirm" onclick="testConfirm()" id="confirm"/>
<input type="button" value="prompt" onclick="testPrompt()" id="prompt"/>
</body>
</html>
相关文章:
Selenium2.0功能测试之Start browsers

posted on 2013-10-18 11:37 顺其自然EVO 阅读(970) 评论(0)  编辑  收藏 所属分类: selenium and watir webdrivers 自动化测试学习


只有注册用户登录后才能发表评论。


网站导航:
 
<2013年10月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜