I have an NUnit test method which looks like this
[Test]
[Property("TestDescription", "Testing Subtraction of Two numbers")]
[NUnit.Framework.CategoryAttribute("mytag,subtract")]
public void TestSubtract()
{
int res = SimpleCalculator.Subtract(10,10);
//some lines of code....
}
我在C#中使用System.Reflection读取这个方法的属性。但是,我一直无法读取 "属性 "属性的值,它是 "TestDescription","测试两个数字的减法"。我还需要读取CategoryAttribute的值。到目前为止,我还不能读取这些值。请帮我解决这个问题。
下面是我的代码。我从一个dll加载程序集。然后,加载所有的类型。对于每个类型,我都在检索方法信息。对于每个方法信息,我正在检索属性。在检索了 "NUnit.Framework.PropertyAttribute "之后,我需要检索它的值。我需要检索它的值。
Assembly a = Assembly.LoadFile(dllPath);
var types = a.GetTypes();
foreach(Type type in types)
{
foreach (MethodInfo methodInfo in type.GetMethods())
{
var attributes = methodInfo.GetCustomAttributes(true);
foreach (var attr in attributes)
{
if ((attr.ToString() == "NUnit.Framework.TestAttribute") || (attr.ToString() ==
"NUnit.Framework.TestCaseAttribute"))
{
//some code
}
else if((attr.ToString() == "NUnit.Framework.PropertyAttribute"))
{
//** need to retrieve the attribute value here.
}
}
}
}
你可以使用 "NUnit.Framework.CategoryAttribute"("mytag,subtract"... Attribute.GetCustomAttributes
来获取所有信息。PropertyAttribute
是有点棘手的,因为你可以为一个键分配多个值。下面是一个例子。
using NUnit.Framework;
using System;
using System.Reflection;
namespace ConsoleApp
{
static class Program
{
static void Main(string[] args)
{
string dllPath = @"C:\Path\To\MyDll.dll";
Assembly a = Assembly.LoadFrom(dllPath);
Type[] types = a.GetTypes();
foreach (Type type in types)
{
foreach (MethodInfo methodInfo in type.GetMethods())
{
PropertyAttribute[] propertyAttributes = (PropertyAttribute[])Attribute.GetCustomAttributes(methodInfo, typeof(PropertyAttribute));
foreach (PropertyAttribute attribute in propertyAttributes)
foreach (string key in attribute.Properties.Keys)
foreach (var value in attribute.Properties[key])
Console.WriteLine($"PropertyAttribute :: Key: {key} :: Value: {value}");
CategoryAttribute[] categoryAttributes = (CategoryAttribute[])Attribute.GetCustomAttributes(methodInfo, typeof(CategoryAttribute));
foreach (CategoryAttribute attribute in categoryAttributes)
Console.WriteLine($"CategoryAttribute :: Name: {attribute.Name}");
}
}
}
}
}