【发布时间】:2012-07-13 03:01:50
【问题描述】:
我需要检查 WebDriver 中是否存在 Alert。
有时会弹出警报,但有时不会弹出。我需要先检查警报是否存在,然后我可以接受或关闭它,否则它会说:未找到警报。
【问题讨论】:
我需要检查 WebDriver 中是否存在 Alert。
有时会弹出警报,但有时不会弹出。我需要先检查警报是否存在,然后我可以接受或关闭它,否则它会说:未找到警报。
【问题讨论】:
public boolean isAlertPresent()
{
try
{
driver.switchTo().alert();
return true;
} // try
catch (NoAlertPresentException Ex)
{
return false;
} // catch
} // isAlertPresent()
在此处查看链接https://groups.google.com/forum/?fromgroups#!topic/webdriver/1GaSXFK76zY
【讨论】:
ExpectedConditions.alertIsPresent() 为您提供完全相同的东西,但以一种更好的方式,并且只需一行 :)
以下(C# 实现,但在 Java 中类似)允许您在不创建 WebDriverWait 对象的情况下确定是否存在警报。
boolean isDialogPresent(WebDriver driver) {
IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver);
return (alert != null);
}
【讨论】:
我建议使用ExpectedConditions 和alertIsPresent()。 ExpectedConditions 是一个包装类,它实现了ExpectedCondition 接口中定义的有用条件。
WebDriverWait wait = new WebDriverWait(driver, 300 /*timeout in seconds*/);
if(wait.until(ExpectedConditions.alertIsPresent())==null)
System.out.println("alert was not present");
else
System.out.println("alert was present");
【讨论】:
我发现在Firefox (FF V20 & selenium-java-2.32.0) 中捕获driver.switchTo().alert(); 的异常非常慢。`
所以我选择了另一种方式:
private static boolean isDialogPresent(WebDriver driver) {
try {
driver.getTitle();
return false;
} catch (UnhandledAlertException e) {
// Modal dialog showed
return true;
}
}
当您的大多数测试用例都不存在对话框时,这是一种更好的方法(抛出异常很昂贵)。
【讨论】:
ExpectedConditions.alertIsPresent更快
我建议使用ExpectedConditions 和alertIsPresent()。 ExpectedConditions 是一个包装类,它实现了ExpectedCondition 接口中定义的有用条件。
public boolean isAlertPresent(){
boolean foundAlert = false;
WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/);
try {
wait.until(ExpectedConditions.alertIsPresent());
foundAlert = true;
} catch (TimeoutException eTO) {
foundAlert = false;
}
return foundAlert;
}
注意:这是基于 nilesh 的回答,但适用于捕获由 wait.until() 方法抛出的 TimeoutException。
【讨论】:
ExpectedConditions 已过时,因此:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent());
【讨论】:
此代码将检查警报是否存在。
public static void isAlertPresent(){
try{
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText()+" Alert is Displayed");
}
catch(NoAlertPresentException ex){
System.out.println("Alert is NOT Displayed");
}
}
【讨论】:
public static void handleAlert(){
if(isAlertPresent()){
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
}
}
public static boolean isAlertPresent(){
try{
driver.switchTo().alert();
return true;
}catch(NoAlertPresentException ex){
return false;
}
}
【讨论】:
公共布尔 isAlertPresent() {
try
{
driver.switchTo().alert();
system.out.println(" Alert Present");
}
catch (NoAlertPresentException e)
{
system.out.println("No Alert Present");
}
}
【讨论】: