什么时候检查意外警报?

我正在使用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;
}
lilipppp 回答:什么时候检查意外警报?

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()函数中获取警报文本。 希望这对您有用!

本文链接:https://www.f2er.com/2970180.html

大家都在问