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

  這樣寫(xiě),代碼量大的話(huà),需要都加,代碼會(huì)很冗余,不建議使用
  實(shí)現(xiàn)事件監(jiān)聽(tīng)接口WebDriverEventListener,alert一般是在click事件之后觸發(fā)的,所以在afterClickOn方法中對(duì)alert進(jìn)行捕獲
@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時(shí)對(duì)alert彈框進(jìn)行全局設(shè)置
@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();
}
  實(shí)現(xiàn)ITestListener接口,對(duì)代碼可能會(huì)拋出的UnexpectedAlertBehaviour異常進(jìn)行捕獲
  1.新建AlertListner類(lèi)實(shí)現(xiàn)ITestListener,并重寫(xiě)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("進(jìn)入onfail 異常catch");
NofindAlert.printStackTrace();
//throw NofindAlert;
}
if(flag) {
alert.accept();
}
}
  2.再建一個(gè)測(cè)試類(lèi),在類(lèi)前面一行加入監(jiān)聽(tīng)@Listeners({ com.elong.air.tools.AlertListner.class }) ,測(cè)試類(lèi)只需要寫(xiě)正常代碼,不需要對(duì)可能會(huì)彈alert的彈框進(jìn)行處理。
@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"));
}
  后這個(gè)方法還存在瑕疵,需要后續(xù)優(yōu)化,歡迎讀者提出改進(jìn)意見(jiàn)。

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