c# - NUnit 重试动态属性

标签 c# selenium nunit

您好,我想通过 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/

相关文章:

c# - LINQ 中的动态 where 子句?

c# - 是否可以做出动态的沮丧?

python - Selenium select第一个选择的选项没有 'value'属性,如何添加此属性?

selenium - 在哪里可以找到 Selenium WebDriver 的 64 位版本 chromedriver.exe?

javascript - 如何从 Selenium 中的日期选择器中选择今天的日期和时间(+15 分钟)

asp.net-core - 使用 nunit 进行 Asp.net Core 单元测试

c# - 是否可以检测到 Stream 是否已被客户端关闭?

c# - 如何以编程方式将单击事件添加到 FrameworkElementFactory

visual-studio - 如何配置 Resharper 使其 "allows"在方法名称中有下划线?

c# - 使用 Moq、Silverlight 和 NUnit 进行单元测试