这样写,代码量大的话,需要都加,代码会很冗余,不建议使用
实现事件监听接口WebDriverEventListener,alert一般是在click事件之后触发的,所以在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();
}
实现ITestListener接口,对代码可能会抛出的UnexpectedAlertBehaviour异常进行捕获
1.新建AlertListner类实现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.再建一个测试类,在类前面一行加入监听@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"));
}
后这个方法还存在瑕疵,需要后续优化,欢迎读者提出改进意见。