NUnit retry dynamic attribute

前端 未结 2 1198
陌清茗
陌清茗 2021-01-19 07:46

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

The app.config has the following line:



        
相关标签:
2条回答
  • 2021-01-19 08:45

    A bit of work around, but you can use TestCaseSource attribute to create 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 test explorer you will see Test(1), Test(2), Test(3).

    0 讨论(0)
  • 2021-01-19 08:46

    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() {
        //.... 
    }
    
    0 讨论(0)
提交回复
热议问题