如何使用System.Reflection检索NUnit测试方法的“属性”属性的值?

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加载程序集。 然后,加载所有类型。对于每种类型,我正在检索methodInfo。 对于每个methodInfo,我都在检索属性。检索后 “ 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.
         }

       }
   } 
}
sayalin 回答:如何使用System.Reflection检索NUnit测试方法的“属性”属性的值?

您可以使用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}");
                }
            }
        }
    }
}
,

为什么不使用NUnit测试上下文?

您将能够获取有关测试的所有必要数据和信息。

请参阅NUnit文档here

本文链接:https://www.f2er.com/2319285.html

大家都在问