Java 如何处理“意外警报打开”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19173195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:44:07  来源:igfitidea点击:

How to handle the "unexpected alert open"?

javaselenium

提问by Buras

I got an issue with Selenium throwing timeout exceptionbecause of a pop up window

timeout exception由于弹出窗口, 我遇到了 Selenium 抛出的问题

  unexpected alert open
  not provide any stacktrace information)
  Command duration or timeout: 5 milliseconds

The alert has OKand CANCELbuttons. I know two ways to handle this

警报有OKCANCEL按钮。我知道两种处理方法



The first way is reopen a new session

第一种方式是重新打开一个新会话

driver.quit();
driver = new ChromeDriver();


Second way is using Robot class

第二种方法是使用 Robot 类

Robot r = new Robot();
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);

However, this methods are not time efficient. Is there any better way?

然而,这种方法并不省时。有没有更好的办法?

采纳答案by Nathan Merrill

This should do the trick:

这应该可以解决问题:

driver.switchTo().alert().accept();

回答by Chetan

Try this,

尝试这个,

public boolean isAlertPresent() {

    boolean presentFlag = false;

    try {

        // Check the presence of alert
        Alert alert = driver.switchTo().alert();
        // Alert present; set the flag
        presentFlag = true;
        // if present consume the alert
        alert.accept();
        //( Now, click on ok or cancel button )

    } catch (NoAlertPresentException ex) {
        // Alert not present
        ex.printStackTrace();
    }

    return presentFlag;
}

I hope this will helpful to you.

我希望这对你有帮助。

回答by Manidhar

If your are using any frameworks like TestNG , you can use Listeners like ITestListener e.t.c where you have to override some of the methods like BeforeCommand and afterCommand. So in BeforeCommand, implement code for alert to dismiss and check the beauty. When ever selenium command is getting executed, this beforeCommand method will call automatically and check whether alert is present or not . If yes it will dismiss and execute your command . I hope it will solve u r problem

如果您正在使用 TestNG 之类的任何框架,则可以使用 ITestListener 之类的侦听器,您必须覆盖一些方法,例如 BeforeCommand 和 afterCommand。因此,在 BeforeCommand 中,实现警报的代码以关闭和检查美观。当 selenium 命令被执行时,这个 beforeCommand 方法将自动调用并检查警报是否存在。如果是,它将关闭并执行您的命令。我希望它能解决你的问题

回答by cogitovirus

Methods to handle alerts in Selenium

Selenium 中处理警报的方法

  1. Decide on each individually
  1. 单独决定每个

If you need some of those alerts in your tests, you have the ability to handle each alert individually using:

如果您在测试中需要其中一些警报,您可以使用以下方法单独处理每个警报:

driver.switchTo().alert().accept();


  1. Handle by default setup
  1. 处理默认设置

To be really time efficient, you can set chrome capabilitesat the start of the test execution to ACCEPT, INGOREor DISMISSalerts by defaultwhen they appear.

为了真正节省时间,您可以在测试执行开始时将 chrome功能设置为ACCEPTINGOREDISMISS警报出现时默认情况下

Example:

例子:

capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);


  1. Using Robot class
  1. 使用机器人类

Robot r = new Robot();

r.keyPress(KeyEvent.VK_ENTER);

r.keyRelease(KeyEvent.VK_ENTER);

机器人 r = 新机器人();

r.keyPress(KeyEvent.VK_ENTER);

r.keyRelease(KeyEvent.VK_ENTER);



  1. Reopen a new session
  1. 重新打开一个新会话

driver.quit();

driver = new ChromeDriver();

驱动程序退出();

驱动程序 = 新的 ChromeDriver();



回答by premganz

More often this issue is bothersome in that it appears at unpredictable places in the system under test. Right now, I dont think there exists ways to handle ALL of these uncretainities automatically by configuration in the webdriver. My general advice would be to wrap the webDriver in a Proxy and use some kind of a dynamic proxy to wrap all the webdriver methods. This way you get a single point of control over unpredictable alerts, get to do logging or evaluate method performance, handle random unreachableBrowser Exceptions, handle random StaleElementException etc. I find this to be very useful for a variety of situations, at a small performance penalty.

更常见的是,这个问题很烦人,因为它出现在被测系统中不可预测的地方。现在,我认为没有办法通过 webdriver 中的配置自动处理所有这些不确定性。我的一般建议是将 webDriver 包装在一个代理中,并使用某种动态代理来包装所有 webdriver 方法。通过这种方式,您可以对不可预测的警报进行单点控制,进行日志记录或评估方法性能,处理随机无法访问的浏览器异常,处理随机 StaleElementException 等。我发现这对于各种情况非常有用,但性能损失很小.

        Class WebDriverProxy implements InvocationHandler{
       WebDriverWrapperImpl impl = new WebDriverWrapperImpl();

        public String clickByXPath(String xpath)  {
            return (String)handleInvocation(impl,"clickByXPath", new Object[]{xpath});
            //  return impl.clickByXPath( xpath) ;
        }


    /**All fail fast strategies could be centralized here., no need of any assertion errors in libraries,
         * However it makes sense to wrap webdriver exceptions as either recoverable or nonrecoverable
         * recoverable ones are like unexpected hangs on the browser, which could be handled at the test runner level, wherein the 
         * whole test can be retried.
         * irrecoverable ones are also mostly handled at the test runner level, but capable of being caught at the test script level *  
         **/
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
        {
            Object o = null;
            Throwable target = null;
            try{
                o = method.invoke(proxy, args);
            }       
            catch(InvocationTargetException ee){            
                target = ee.getTargetException();
                throw target;
            }
            return o;
        }

        public Object handleInvocation(Object proxy, String method, Object[] args){     

            Object toReturn = null;
            Method m = null;
            Class[] classes = new Class[args.length];
            for(int i = 0;i<args.length;i++){
                classes[i]=String.class;
            }
            for(Object x:args){
            logBuffer.append(x.toString()+","); 
            }
            log.trace("WebDriverProxy. "+method+"("+logBuffer.toString()+")");
            logBuffer = new StringBuffer();
            try{
                 m = proxy.getClass().getMethod(method,classes);

                toReturn = invoke(proxy,m, args);

            }catch(NoSuchMethodException e){    
                e.printStackTrace();

            }catch( StaleElementReferenceException e){
                log.debug("Exception was of tye "+e.getClass().getCanonicalName());






            }
            catch(UnreachableBrowserException | NoSuchElementException e){
                log.debug("Exception was of tye "+e.getClass().getCanonicalName());
                //If the NoSuchelement is due to suspect Alerts being present, switchToAlert() and alert.accept() here.
            }



            return toReturn;
        }



        }


class WebDriverWrapperImpl {
 WebDriver driver = new ChromeDriver();
  public String clickByXPath(String xpath)  throws Exception{
            driver.findElement(By.Xpath(xpath)).click();
            return driver.getTitle();
        }

}

回答by Alan

Configure DesiredCapabilitiesto accept unexpected alter behavior.

配置DesiredCapabilities为接受意外的更改行为。

final DesiredCapabilities chromeCapabilities = DesiredCapabilities.chrome();
chromeCapabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);
final ChromeOptions chromeOptions = new ChromeOptions();
/*
 * Other options...
 */
chromeCapabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
ChromDrvier driver = new ChromeDriver(chromeCapabilities);

回答by akash

ChromeOptions options = new ChromeOptions();
options.setUnhandledPromptBehaviour(ACCEPT);
WebDriver driver = new ChromeDriver(options);

Instead of ACCEPTyou can pass the following enum constants ACCEPT, ACCEPT_AND_NOTIFY, DISMISS, DISMISS_AND_NOTIFY, IGNOREaccording to your requirement.

相反的ACCEPT,你可以通过以下枚举常量ACCEPTACCEPT_AND_NOTIFYDISMISSDISMISS_AND_NOTIFYIGNORE根据您的要求。