2013-10-06 5 views
1
using System; 
using OpenQA.Selenium; 

namespace MyApplication.Selenium.Tests.Source 
{ 
    public sealed class MyExpectedConditions 
    { 

     private void ExpectedConditions() 
     { 
     } 

     public static Func<IWebDriver, IAlert> AlertIsPresent() 
     { 
      return (driver) => 
      { 
       try 
       { 
        return driver.SwitchTo().Alert(); 
       } 
       catch (NoAlertPresentException) 
       { 
        return null; 
       } 
      }; 
     } 

    } 
} 

Vous pouvez l'utiliser comme ceci:Comment mettre en œuvre ExpectedConditions.AlertIsPresent en C#

new WebDriverWait(Driver, TimeSpan.FromSeconds(5)) { Message = "Waiting for alert to appear" }.Until(d => MyExpectedConditions.AlertIsPresent()); 
Driver.SwitchTo().Alert().Accept(); 
+0

Le WebDriverWait retour OK et il des erreurs sur la ligne suivante? – Arran

Répondre

4

WebDriverWait lancera une exception WebDriverTimeoutException si alerte ne se trouve pas dans la période d'attente requise.

Utilisez un bloc try catch autour de WebDriverWait pour attraper WebDriverTimeoutException.

J'utilise une méthode d'extension comme ci-dessous:

public static IAlert WaitGetAlert(this IWebDriver driver, int waitTimeInSeconds = 5) 
{ 
    IAlert alert = null; 

    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(waitTimeInSeconds)); 

    try 
    { 
     alert = wait.Until(d => 
      { 
       try 
       { 
        // Attempt to switch to an alert 
        return driver.SwitchTo().Alert(); 
       } 
       catch (NoAlertPresentException) 
       { 
        // Alert not present yet 
        return null; 
       } 
      }); 
    } 
    catch (WebDriverTimeoutException) { alert = null; } 

    return alert; 
} 

et l'utiliser comme ceci:

var alert = this.Driver.WaitGetAlert(); 
if (alert != null) 
{ 
    alert.Accept(); 
} 
Questions connexes