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" οnclick="testAlert()" id="alert"/>
<input type="button" value="confirm" οnclick="testConfirm()" id="confirm"/>
<input type="button" value="prompt" οnclick="testPrompt()" id="prompt"/>
</body>
</html>



最新内容请见作者的GitHub页:http://qaseven.github.io/
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值