Passing dynamically generated value to NUnit Custom Attribute

╄→尐↘猪︶ㄣ 提交于 2019-12-24 18:27:07

问题


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 ?


回答1:


You can't do as you asked but you can look at the problem differently. Just give the attribute the name of some property in the JSON file to be examined, e.g. "Config".




回答2:


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.
}


来源:https://stackoverflow.com/questions/47354926/passing-dynamically-generated-value-to-nunit-custom-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!