RetryAttribute
Specifies that a test method should be rerun on failure up to the specified
maximum number of times.
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Commands;
using System;
using System.Runtime.CompilerServices;
namespace NUnit.Framework
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class RetryAttribute : NUnitAttribute, IRepeatTest, ICommandWrapper
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public class RetryCommand : DelegatingTestCommand
{
private readonly int _tryCount;
public RetryCommand(TestCommand innerCommand, int tryCount)
: base(innerCommand)
{
_tryCount = tryCount;
}
public override TestResult Execute(TestExecutionContext context)
{
int num = _tryCount;
while (num-- > 0) {
try {
context.CurrentResult = innerCommand.Execute(context);
} catch (Exception ex) {
if (context.CurrentResult == null)
context.CurrentResult = context.CurrentTest.MakeTestResult();
context.CurrentResult.RecordException(ex);
}
if (context.CurrentResult.ResultState != ResultState.Failure)
break;
if (num > 0) {
context.CurrentResult = context.CurrentTest.MakeTestResult();
context.CurrentRepeatCount++;
}
}
return context.CurrentResult;
}
}
private readonly int _tryCount;
public RetryAttribute(int tryCount)
{
_tryCount = tryCount;
}
[System.Runtime.CompilerServices.NullableContext(1)]
public TestCommand Wrap(TestCommand command)
{
return new RetryCommand(command, _tryCount);
}
}
}