Selenium2.0功能測試之Alert/Confirm/Prompt的處理
WebDriver中處理原生JS的 alert confirm 以及prompt是很方便的(雖然現(xiàn)在原生JS的實現(xiàn)方式用的很少了)。具體思路是使用switchTo.alert()方法定位到當前的alert/confirm/prompt(這里注意當前頁面只能同時含有一個控件,如果多了會報錯的,所以這就需要一一處理了),然后在調(diào)用Alert的方法進行操作,Alert提供了以下幾個方法:
getText : 返回alert/confirm/prompt中的文字內(nèi)容
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(); //創(chuàng)建一個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中輸入內(nèi)容 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> |
posted on 2013-10-18 11:37 順其自然EVO 閱讀(978) 評論(0) 編輯 收藏 所屬分類: selenium and watir webdrivers 自動化測試學習