Dynamic NUnit retry attribute
Hello, I want to dynamically pass the number of retries from app.config value.
The app.config file has the following line:
<add key="retryTest" value="3"/>
And I have defined this variable:
public static readonly int numberOfRetries = int.Parse(ConfigurationManager.AppSettings["retryTest"]);
Finally, I would like to pass this variable as a parameter to the NUnit Retry attribute:
[Test, Retry(numberOfRetries)]
public void Test()
{
//....
}
But I am getting the following error:
"The attribute argument must be a constant expression, typeof expression, or an expression to create an array of an attribute parameter of type"
How can I pass this value dynamically?
source to share
Until I am fully aware of RetryAttribute
. One possible way to achieve the desired functionality would be to extend its current functionality.
/// <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) {
}
}
And then apply the custom attribute.
[Test]
[RetryDynamic]
public void Test() {
//....
}
source to share
A bit about work, but you can use the attribute TestCaseSource
to create a data driven test that will run numberOfRetries
times
[Test, TestCaseSource("GetNum")]
public void Test(int testNum)
{
}
private IEnumerable GetNum
{
get
{
int numberOfRetries = int.Parse(ConfigurationManager.AppSettings["retryTest"]);
for (int i = 1; i <= numberOfRetries; ++i)
{
yield return new TestCaseData(i);
}
}
}
In the test, you will see the conductor Test(1)
, Test(2)
, Test(3)
.
source to share