[英]How to implement ExpectedConditions.AlertIsPresent in C#
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;
}
};
}
}
}
你可以像這樣使用它:
new WebDriverWait(Driver, TimeSpan.FromSeconds(5)) { Message = "Waiting for alert to appear" }.Until(d => MyExpectedConditions.AlertIsPresent());
Driver.SwitchTo().Alert().Accept();
如果在所需的等待期內未找到警報, WebDriverWait
將拋出WebDriverTimeoutException
異常。
在WebDriverWait
周圍使用try catch塊來捕獲WebDriverTimeoutException
。
我使用如下的擴展方法:
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;
}
並像這樣使用它:
var alert = this.Driver.WaitGetAlert();
if (alert != null)
{
alert.Accept();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.