如何使用反射检索测试夹具的类别属性



我有一个NUnit测试项目。在这方面,我有一个像这样的课程

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

如果您注意到,这个类有一个Category属性,它被称为Category("a"(。我想使用反射来检索category属性的值。为此,我正在尝试以下代码:

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属性。那么,我应该如何检索Category属性呢?

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

试试这样的东西:

public void MyMethod()
{
string dllPath = @"C:PathToDll.dll";
Type[] types = Assembly.LoadFrom(dllPath).GetTypes();
foreach (Type type in types)
{
IEnumerable<TestFixtureAttribute> textFixtures = type.GetCustomAttributes<TestFixtureAttribute>();
if (textFixtures.Any())
{
IEnumerable<CategoryAttribute> categories = type.GetCustomAttributes<CategoryAttribute>();
foreach (CategoryAttribute category in categories)
Console.WriteLine($"Type: {type}; CategoryAttribute :: Name: {category.Name}");
}
}
}

或者更短的版本,而不检查TextFixtureAttribute:

public void MyMethod()
{
string dllPath = @"C:PathToDll.dll";
Type[] types = Assembly.LoadFrom(dllPath).GetTypes();
foreach (Type type in types)
{
IEnumerable<CategoryAttribute> categories = type.GetCustomAttributes<CategoryAttribute>();
foreach (CategoryAttribute category in categories)
Console.WriteLine($"Type: {type}; CategoryAttribute :: Name: {category.Name}");
}
}

更简单。。。

运行OneTimeSetUp方法时,TestContext中的类别可用。。。

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

最新更新