Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit retry dynamic attribute

Tags:

c#

selenium

nunit

Hello I want to pass the number of retries dynamically from app.config value.

The app.config 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 that variable as a parameter to Retry NUnit attribute:

[Test, Retry(numberOfRetries)]
public void Test()
{
    //.... 
}

But I get the following error:

"An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type"

How can I dynamically pass that value?

like image 813
joudaon Avatar asked Jan 04 '23 00:01

joudaon


1 Answers

While I am not fully aware of the RetryAttribute. One possible way of achieving 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() {
    //.... 
}
like image 145
Nkosi Avatar answered Jan 20 '23 14:01

Nkosi