我从此帖子中获取了以下自定义RetryAttribute
:NUnit retry dynamic attribute。它工作正常但是当我在Selenium中出现超时错误时它无效。
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
wait.Until(ExpectedConditions.ElementToBeClickable(element));
重试自定义属性:
/// <summary>
/// RetryDynamicAttribute may be applied to test case in order
/// to run it multiple times based on app setting.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class RetryDynamicAttribute : RetryAttribute {
private const int DEFAULT_TRIES = 1;
static Lazy<int> numberOfRetries = new Lazy<int>(() => {
int count = 0;
return int.TryParse(ConfigurationManager.AppSettings["retryTest"], out count) ? count : DEFAULT_TRIES;
});
public RetryDynamicAttribute() :
base(numberOfRetries.Value) {
}
}
然后应用自定义属性。
[Test]
[RetryDynamic]
public void Test() {
//....
}
如何解决这个问题?
答案 0 :(得分:5)
另一种解决方案是实现自己的RetryAttribute
以捕获WebDriver异常。这样你就不必改变测试:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class RetryAttributeEx : PropertyAttribute, IWrapSetUpTearDown
{
private int _count;
public RetryAttributeEx(int count) : base(count) {
_count = count;
}
public TestCommand Wrap(TestCommand command) {
return new RetryCommand(command, _count);
}
public class RetryCommand : DelegatingTestCommand {
private int _retryCount;
public RetryCommand(TestCommand innerCommand, int retryCount)
: base(innerCommand) {
_retryCount = retryCount;
}
public override TestResult Execute(TestExecutionContext context) {
for (int count = _retryCount; count-- > 0; ) {
try {
context.CurrentResult = innerCommand.Execute(context);
}
catch (WebDriverTimeoutException ex) {
if (count == 0)
throw;
continue;
}
if (context.CurrentResult.ResultState.Status != ResultState.Failure.Status)
break;
if (count > 0)
context.CurrentResult = context.CurrentTest.MakeTestResult();
}
return context.CurrentResult;
}
}
}
答案 1 :(得分:4)
根据此处的文件
NUnit文档Retry Attribute
如果测试有意外异常,则返回错误结果 它没有重试。 只有断言失败才能触发重试。至 将意外异常转换为断言失败,请参阅 ThrowsConstraint
强调我的。
相关ThrowsNothingConstraint只是声明代表 不会抛出异常。
如果不期望异常,您需要捕获异常并导致断言失败。
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
Assert.That(() => {
wait.Until(ExpectedConditions.ElementToBeClickable(element));
}, Throws.Nothing);
所以上面的代码只是说执行动作而不应该期待异常。如果抛出异常,那么它是一个失败的断言。如果将属性应用于测试,则将执行重试。