我在等待WebElement可点击时使用DefaultWait。尽管TargetInvocationException是我在等待期间需要囤积的异常列表中的异常之一,但在达到TimeOut周期之前,我仍然会遇到此异常的测试失败。这不是我的预期。
public static void WaitAndClick(this IWebDriver driver, IWebElement webelement)
{
DefaultWait<IWebDriver> fluentWait = new DefaultWait<IWebDriver>(driver)
{
Timeout = TimeSpan.FromSeconds(Configuration.WaitTime.TotalSeconds),
PollingInterval = TimeSpan.FromMilliseconds(500)
};
fluentWait.IgnoreExceptionTypes(typeof(TargetInvocationException),typeof(NoSuchElementException),typeof(InvalidOperationException));
fluentWait.Until(ExpectedConditions.ElementToBeClickable(webelement));
webelement.Click();
}
答案 0 :(得分:0)
尝试使用WebDriverWait
代替DefaultWait<IWebDriver>
,这基本上是相同的。
public static void WaitAndClick(this IWebDriver driver, IWebElement webelement)
{
WebDriverWait fluentWait = new WebDriverWait(driver,Configuration.WaitTime.TotalSeconds);
//No need to set PollingInterval, default is already 500ms
fluentWait.IgnoreExceptionTypes(typeof(TargetInvocationException),typeof(NoSuchElementException),typeof(InvalidOperationException));
fluentWait.Until(ExpectedConditions.ElementToBeClickable(webelement));
webelement.Click();
}
当完全相同的原因(等待webDriver)有预定义的具体类时,我认为不需要使用Interface。如果问题仍然存在,请回报。
更新:如果它不能解决您的问题,请使用lamba表达式来解析Until()(public TResult Until<TResult>(Func<T, TResult> condition);
)所需的函数
fluentWait.Until(driver =>
{
try
{
driver.FindElement(/*By Locator*/).Click();
}
catch (Exception ex)
{
Type exType = ex.GetType();
if (exType == typeof(TargetInvocationException) ||
exType == typeof(NoSuchElementException) ||
exType == typeof(InvalidOperationException))
{
return false; //By returning false, wait will still rerun the func.
}
else
{
throw; //Rethrow exception if it's not ignore type.
}
}
return true;
});
答案 1 :(得分:0)
感谢Thodoris Koskinopoulos,这个解决方案对我来说很好:
public static void WaitAndClick(this IWebDriver driver, IWebElement webelement)
{
var fluentWait = new WebDriverWait(driver, Configuration.WaitTime);
fluentWait.Until(webDriver =>
{
try
{
webelement.Click();
}
catch (Exception ex)
{
if (ex is TargetInvocationException ||
ex is NoSuchElementException ||
ex is InvalidOperationException)
{
return false; //By returning false, wait will still rerun the func.
}
{
throw; //Rethrow exception if it's not ignore type.
}
}
return true;
});
}