首页 > 解决方案 > 何时检查意外警报?

问题描述

我正在使用 Chromedriver、Selenium 和 Java 编写自动化程序。一步调用一种方法,该方法执行类似的操作

 save.click() 

单击保存按钮。有时这只是保存,有时它会引起警报(比如请填写日期字段或你有什么)。

所以我有类似的代码

 page.save(); // which calls the above method
 String alertMsg = waitForAlertTextAndClose(30);

(正如它所说,waitForAlertMessageAndClose() 基本上会等待警报并关闭。如果您想查看它,我将在下面更远地发布代码。

有时在单击保存后,进入下一步会导致 StaleElementReferenceException,因为页面尚未从保存完成加载。

所以我添加了这个 (waitForStaleElement() 只是等待一个陈旧的元素并设置一个 AssertionError 如果该元素没有陈旧并且 waitForXPathVisibility() 等待 xpath 或抛出一个断言。在这种情况下,我不在乎它是否没有不会过时,因为有时它不会。

我修改了保存:

 try {
    save.click();
    waitForStaleElement("Save to go stale", save);
    waitForXpathVisibility("SAVE button", saveXPath);
 } catch (AssertionError ex) {
   ; // this is OK because sometimes it won't go stale
 }

麻烦的是,现在当有一个警报时,它会在方法中抛出一个 UnexpectedAlertOpenError 并且永远不会传播回调用者。

所以我只是好奇。Chromedriver 在哪些点(或执行)会抛出 UnexpectedAlertOpenError?在我添加等待之前它没有这样做。

--- waitForAlertTextAndClose:

public String waitForAlertTextAndClose(int timeOutInSeconds) {
    String alertMessage = null;
    Alert element = null;
    WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
    try {
        element = wait.until(ExpectedConditions.alertIsPresent());
        alertMessage = element.getText();
        element.accept();
    } catch (TimeoutException e) {
        throw new AssertionError("Alert not present after " + timeOutInSeconds + " seconds.");
    }
    return alertMessage;
}

标签: selenium-chromedriveralert

解决方案


public static void AcceptAlert(IWebDriver driver, WebDriverWait wait)
{
  IAlert alert = wait.Until<IAlert>(alrt => WaitForAlert(driver));
  driver.SwitchTo().Alert().Accept();

}

public static IAlert WaitForAlert(IWebDriver driver)
{
  try
  {
    return driver.SwitchTo().Alert();
  }
  catch (NoAlertPresentException)
  {
    return null;
  }
}

如上所述,您可以简单地单独尝试警报并在 AcceptAlert() 函数中获取警报文本。希望这对你有用!


推荐阅读