您的位置:軟件測試 > 開源軟件測試 > 開源功能測試工具 > Selenium
Selenium對Alert彈框的多種處理
作者:喬葉葉 發(fā)布時間:[ 2016/7/6 11:54:42 ] 推薦標簽:功能測試 軟件測試工具

  這樣寫,代碼量大的話,需要都加,代碼會很冗余,不建議使用
  實現(xiàn)事件監(jiān)聽接口WebDriverEventListener,alert一般是在click事件之后觸發(fā)的,所以在afterClickOn方法中對alert進行捕獲
@Override
public void afterClickOn(WebElement arg0, WebDriver arg1) {
// TODO Auto-generated method stub
boolean flag = false;
Alert alert = null;
try {
new WebDriverWait(arg1, 10).until(ExpectedConditions
.alertIsPresent());
alert = arg1.switchTo().alert();
flag = true;
// alert.accept();
} catch (NoAlertPresentException NofindAlert) {
// TODO: handle exception
NofindAlert.printStackTrace();
// throw NofindAlert;
}
if (flag) {
alert.accept();
}
}
  在初始化webdriver時對alert彈框進行全局設置
@Test(enabled = false)
public void ff5() {
System.setProperty(key, value);
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR,
UnexpectedAlertBehaviour.ACCEPT);
driver = new ChromeDriver(dc);
driver.get("file:///Users/user/Documents/qiaojiafei/seleniumtest.html");
driver.findElement(By.xpath("//*[@id='alert']/input")).click();
driver.findElement(By.xpath("//*[@id='alert']/input")).click();
}
  實現(xiàn)ITestListener接口,對代碼可能會拋出的UnexpectedAlertBehaviour異常進行捕獲
  1.新建AlertListner類實現(xiàn)ITestListener,并重寫onTestFailure方法
@Override
public void onTestFailure(ITestResult result) {
// TODO Auto-generated method stub
System.out.println("into failure test");
Throwable throwable = result.getThrowable();
if(throwable instanceof UnhandledAlertException) {
System.out.println("get UnhandledAlertException la"+throwable.toString());
AlertListnerTest tb = (AlertListnerTest) result.getInstance();
WebDriver driver = tb.getDriver();
Alert alert = null;
boolean flag = false;
try {
new WebDriverWait(driver,10).until(ExpectedConditions.alertIsPresent());
alert = driver.switchTo().alert();
flag = true;
//alert.accept();
} catch (NoAlertPresentException NofindAlert) {
// TODO: handle exception
System.out.println("進入onfail 異常catch");
NofindAlert.printStackTrace();
//throw NofindAlert;
}
if(flag) {
alert.accept();
}
}
  2.再建一個測試類,在類前面一行加入監(jiān)聽@Listeners({ com.elong.air.tools.AlertListner.class }) ,測試類只需要寫正常代碼,不需要對可能會彈alert的彈框進行處理。
@Test
public void ff6() {
System.out.println("jinru ff6test");
System.setProperty(key, value);
driver = new ChromeDriver();
driver.get("file:///Users/user/Documents/qiaojiafei/seleniumtest.html");
driver.findElement(By.xpath("//*[@id='alert']/input")).click();
driver.findElement(By.xpath("//*[@id='alert']/input"));
}
  后這個方法還存在瑕疵,需要后續(xù)優(yōu)化,歡迎讀者提出改進意見。

上一頁12下一頁
軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd