天天看點

Selenium2.0功能測試之Alert/Confirm/Prompt的處理

   webdriver中處理原生js的 alert confirm 以及prompt是很友善的(雖然現在原生js的實作方式用的很少了)。具體思路是使用switchto.alert()方法定位到目前的alert/confirm/prompt(這裡注意目前頁面隻能同時含有一個控件,如果多了會報錯的,是以這就需要一一處理了),然後在調用alert的方法進行操作,alert提供了以下幾個方法:

  gettext : 傳回alert/confirm/prompt中的文字内容

  accept : 點選确認按鈕

  dismiss : 點選取消按鈕如果有取消按鈕的話

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();

alert confirm = driver.switchto().alert();  //捕獲confirm

string confirmtext = confirm.gettext(); //擷取confirm中的文字資訊

system.out.println(confirmtext);

confirm.accept();  //confirm 點選确認按鈕

//      confirm.dismiss();  //confirm點選取消按鈕

//點選彈出prompt

driver.findelement(by.id("prompt")).click();

alert prompt = driver.switchto().alert();  //捕獲prompt

//      string prompttext = prompt.gettext(); //擷取prompt中的文字資訊

//      system.out.println(prompttext);

prompt.sendkeys("可能是由于太懶了");  //向prompt中輸入内容

prompt.accept();  //prompt 點選确認按鈕

//      prompt.dismiss();  //prompt點選取消按鈕

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>

最新内容請見作者的github頁:http://qaseven.github.io/

繼續閱讀