您好,我想通过 app.config 值动态传递重试次数。
app.config 包含以下行:
<add key="retryTest" value="3"/>
我已经定义了这个变量:
public static readonly int numberOfRetries = int.Parse(ConfigurationManager.AppSettings["retryTest"]);
最后我想将该变量作为参数传递给 Retry NUnit 属性:
[Test, Retry(numberOfRetries)]
public void Test()
{
//....
}
但是我得到以下错误:
"An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type"
如何动态传递该值?
最佳答案
虽然我不完全了解 RetryAttribute
.实现所需功能的一种可能方法是扩展其当前功能。
/// <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() {
//....
}
关于c# - NUnit 重试动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44040612/