使用Reflection解析函数/方法内容

我的unit testing框架包括TestFixtures,TestMethods和Actions。 Action是TestMethod中的另一个小容器,Actions来自我们公司编写的内部Dll。 在这样的方法中使用动作:

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

我必须编写一个应用程序,它从DLL收集有关夹具,测试和操作的所有信息。 我已经找到了如何使用类型/方法属性通过reflection枚举测试夹具和测试方法。

但是我不知道如何在测试方法中枚举动作。

能否请你帮忙? 是否可以使用reflection?

更新:见接受的答案。 真的很酷的图书馆。 你也可以在这里看看( WPF:以MVVM方式逐步教程中的Binding TreeView ),如果你对如何为夹具,测试和操作创建实体模型以及以MVVM方式绑定到TreeView感兴趣。

是的。

reflection将为您提供方法体,而不是您需要反汇编IL来读取方法体并获取您想要的任何信息。

 var bytes = mi.GetMethodBody().GetILAsByteArray(); 

拆卸的可能工具之一是塞西尔

查看Traverse ac#方法和anazlye方法体以获取更多链接。

而不是使用reflection,为什么不推出自己的方法来记录所有Action执行。

 void ExecuteAction(Action action) { //Log TestFixture, TestMethod, Action //Execute actual action } [Test] void TestMethod1() { ExecuteAction(Run(new Sleep { Seconds = 10 } )); } 

ExecuteAction方法可以在base或helper类中

谢谢,阿列克谢莱文科夫! 最后我找到了一个使用你的小费的解决方案。 共享。 你应该做的唯一的事情 – >从https://github.com/jbevain/mono.reflection下载并引用Mono.Reflection.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); } } } } } }