[英]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;
}
};
}
}
}
You can use it like this: 你可以像这样使用它:
new WebDriverWait(Driver, TimeSpan.FromSeconds(5)) { Message = "Waiting for alert to appear" }.Until(d => MyExpectedConditions.AlertIsPresent());
Driver.SwitchTo().Alert().Accept();
WebDriverWait
will throw a WebDriverTimeoutException
exception if alert is not found in the required wait period. 如果在所需的等待期内未找到警报, WebDriverWait
将抛出WebDriverTimeoutException
异常。
Use a try catch block around WebDriverWait
to catch WebDriverTimeoutException
. 在WebDriverWait
周围使用try catch块来捕获WebDriverTimeoutException
。
I use an extension method like below: 我使用如下的扩展方法:
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;
}
and use it like this: 并像这样使用它:
var alert = this.Driver.WaitGetAlert();
if (alert != null)
{
alert.Accept();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.