Make IAlert as Observer

后端 未结 1 1539
盖世英雄少女心
盖世英雄少女心 2021-01-28 23:16

I\'m using last selenium some websites have randomly popup messages that stops the normally test process

What i\'m thinking is that i need to do IAlert as Observer patte

相关标签:
1条回答
  • 2021-01-28 23:42

    Since popup would matter when you are trying to do something else, I will suggest the following approach: EventFiringWebDriver allows you to define custom code that will run right before or after a particular event. See an example here.

    Unfortunately I didn't write anything on .Net for a long time, so my C# skills are rusty. So roughly it would look like this:

    IWebDriver driver = new FirefoxDriver();
    EventFiringWebDriver eventDriver = new EventFiringWebDriver(driver);
    // add all relevant events, for example before clicking on something:
    eventDriver.ElementClicking = new EventHandler<FindElementEventArgs>(checkPopup);
    driver = eventDriver; // only need EventFiringWebDriver
    

    And then

    static void checkPopup(object sender, OpenQA.Selenium.Support.Events. WebElementEventArgs e) {
         EventFiringWebDriver driver = (sender as OpenQA.Selenium.Support.Events.EventFiringWebDriver);
         try {
             Alert alert = driver.SwitchTo().Alert();
             alert.accept();
         }
         catch (NoAlertPresentException ex) { 
             // nothing to do - just continue
         }
    }
    

    So now, every time script is about to click something, it would first check for popup and accept it if needed.

    0 讨论(0)
提交回复
热议问题