首页 > 解决方案 > 如何使用反射检索测试夹具的类别属性?

问题描述

我有一个 NUnit 测试项目。因为我有这样的课

    [TestFixture]
    [Category("A")]
    public class SmokeTest
    {

    }

如果您注意到,该类有一个 Category 属性,称为 Category("A")。我想使用反射检索类别属性的值。为此,我正在尝试以下代码:

public void MyMethod()
{           
     Assembly executingAssembly = Assembly.LoadFrom("dllpath");
     var types = executingAssembly.GetTypes();
     foreach (Type type in types)
     {
       var testFixtureAttrList = Attribute.GetCustomAttributes(type, typeof(TestFixtureAttribute));
       if (testFixtureAttrList.Length > 0)
       {
CategoryAttribute[] categoryAttributes = (CategoryAttribute[])Attribute.GetCustomAttributes(type, typeof(CategoryAttribute));
           foreach (CategoryAttribute attribute in categoryAttributes)
           {
               Console.WriteLine($"CategoryAttribute :: Name: {attribute.Name}");

           }//FOR-EACH ENDS
      }
   }
}

但是,到目前为止,我还无法使用此代码检索类别属性。那么,我应该怎么做才能检索 Category 属性?

我的代码是用 C# 编写的。我的解决方案是使用 .NET Core 3.1 构建的

标签: c#.net-corenunitsystem.reflectionnunit-3.0

解决方案


更简单的...

TestContext运行该方法时,您可以使用类别OneTimeSetUp...

...
IEnumerable<CategoryAttribute> fixtureCategories;

[OneTimeSetUp]
public void MyOneTimeSetUpMethod()
{
    fixtureCategories =
        TestContext.CurrentContext.Test.Properties["Category"]);
}

推荐阅读