Search code examples
attributesnunitconstantstypeofcustom-attribute

Passing dynamically generated value to NUnit Custom Attribute


For our test scenarios - based on configuration of the application, we may want to either enable or disable a scenario. For this purpose, I created a custom IgnoreIfConfig Attribute like this :

public class IgnoreIfConfigAttribute : Attribute, ITestAction
{
    public IgnoreIfConfigAttribute(string config)
    {
        _config = config;
    }
    public void BeforeTest(ITest test)
    {
        if (_config != "Enabled") NUnit.Framework.Assert.Ignore("Test is Ignored due to Access level");
    }
    public void AfterTest(ITest test)
    { 

    }
    public ActionTargets Targets { get; private set; }
    public string _config { get; set; }
}

Which can be used as follows :

    [Test, Order(2)]
    [IgnoreIfConfig("Enabled")] //Config.Enabled.ToString()
    public void TC002_DoTHisIfEnabledByConfig()
    {

    }

Now This attribute would only take a constant string as an input. If I were to replace this with something generated dynamically at the runtime, Such as a value from Json file - How can I convert it to a Constant. Constant Expression, TypeOf Expression or Array Creation Expression of Attribute parameter type ? Such as Config.Enabled ?


Solution

  • As per Charlie's suggestion : I implemented it like this -

    PropCol pc = new PropCol(); // Class where the framework reads Json Data.
    public IgnoreIfConfigAttribute(string config)
    {
        pc.ReadJson();
        if(config = "TestCase") _config = PropCol.TestCase;
        // Here TestCase is a Json element which is either enabled or disabled.
    }