C# 使用反射解析函数/方法内容

C# 使用反射解析函数/方法内容,c#,unit-testing,reflection,C#,Unit Testing,Reflection,我的单元测试框架由testfixture、TestMethods和action组成。Action是TestMethod中附加的较小容器,Actions来自我们公司编写的内部Dll。操作在以下方法中使用: [Test] void TestMethod1() { Run(new Sleep { Seconds = 10 } ); } 我必须编写一个应用程序,它从DLL中收集有关装置、测试和操作的所有信息。我发现了如何使用类型/方法属性通过反射枚举测试装置和测试方法 但我不知道如何枚举测试方

我的单元测试框架由testfixture、TestMethods和action组成。Action是TestMethod中附加的较小容器,Actions来自我们公司编写的内部Dll。操作在以下方法中使用:

[Test]
void TestMethod1()
{
    Run(new Sleep { Seconds = 10 } );
}
我必须编写一个应用程序,它从DLL中收集有关装置、测试和操作的所有信息。我发现了如何使用类型/方法属性通过反射枚举测试装置和测试方法

但我不知道如何枚举测试方法中的操作

你能帮忙吗?是否有可能使用反射来实现呢

更新: 见公认的答案。非常酷的图书馆。如果您对我如何为装置、测试和操作创建实体模型以及如何以MVVM方式绑定到TreeView感兴趣,也可以在这里查看()。

是的

反射将为您提供方法体,而您需要反汇编IL来读取方法体并获得所需的任何信息

var bytes = mi.GetMethodBody().GetILAsByteArray();
一个可能的工具是


查看更多链接。

与其使用反射,不如推出自己的方法来记录所有动作执行情况

void ExecuteAction(Action action)
{
   //Log TestFixture, TestMethod, Action

   //Execute actual action
}

[Test]
void TestMethod1()
{
    ExecuteAction(Run(new Sleep { Seconds = 10 } ));
}

ExecuteAction方法可以在基类或助手类中

谢谢,Alexei Levenkov!最后,我用你的建议找到了解决办法。分享。您唯一应该做的事情是->从下载并引用Mono.Reflection.dll


谢谢你的回答。你的意思是:每个动作之前,每个动作之后,等等。?但是它不合适。我能够在运行时记录正在运行的操作。但我必须从DLL中收集所有信息,而不是在运行时运行期间。
using System;
using System.Linq;
using System.Reflection;
using MINT;
using MbUnit.Framework;
using Mono.Reflection;

namespace TestDll
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            const string DllPath = @"d:\SprinterAutomation\Actions.Tests\bin\x86\Debug\Actions.Tests.dll";
            Assembly assembly = Assembly.LoadFrom(DllPath);

            // enumerating Fixtures
            foreach (Type fixture in assembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(TestFixtureAttribute), false).Length > 0)) 
            {
                Console.WriteLine(fixture.Name);
                // enumerating Test Methods
                foreach (var testMethod in fixture.GetMethods().Where(m => m.GetCustomAttributes(typeof(TestAttribute), false).Length > 0))
                {
                    Console.WriteLine("\t" + testMethod.Name);
                    // filtering Actions
                    var instructions = testMethod.GetInstructions().Where(
                        i => i.OpCode.Name.Equals("newobj") && ((ConstructorInfo)i.Operand).DeclaringType.IsSubclassOf(typeof(BaseAction)));

                    // enumerating Actions!
                    foreach (Instruction action in instructions)
                    {
                        var constructroInfo = action.Operand as ConstructorInfo;
                        Console.WriteLine("\t\t" + constructroInfo.DeclaringType.Name);
                    }
                }
            }

        }
    }
}