C# 向方法动态注入属性

C# 向方法动态注入属性,c#,unit-testing,C#,Unit Testing,在单元测试期间,我需要用测试属性装饰我的方法,如下所示: [Test] public class when_1_is_passed : specifications_for_prime_test { public void should_return_false() { Assert.AreEqual(1,1); } } [Test]属性表示方法是测试方法。我想去掉[Test]属性。在95%的情况下,测

在单元测试期间,我需要用测试属性装饰我的方法,如下所示:

[Test] 
 public class when_1_is_passed : specifications_for_prime_test
    {
        public void should_return_false()
        {
            Assert.AreEqual(1,1);
        }
    }
[Test]属性表示方法是测试方法。我想去掉[Test]属性。在95%的情况下,测试套件中定义的所有方法都是测试方法。其他5%可以是初始化代码等

无论如何,现在我需要将TestAttribute动态地注入到所有方法中。我有以下代码,但我没有看到在方法上注入属性的方法

public static void Configure<T>(T t)
        {
            var assemblyName = "TestSuite";
            var assembly = Assembly.Load(assemblyName);

            var assemblyTypes = assembly.GetTypes();

            foreach (var assemblyType in assemblyTypes)
            {
                if(assemblyType.BaseType == typeof(specifications_for_prime_test)) 
                {
                    // get all the methods from the class and inject the TestMethod attribute 

                    var methodInfos = assemblyType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.DeclaredOnly); 
                    foreach(var methodInfo in methodInfos)
                    {
                        // now attach the TestAttribute to the method
                    }
                }
            }

            var methodsInfo = t.GetType().GetMethods();  
        }

您可以利用吗?

如果您不使用Test属性修饰测试方法,而是使用Test作为测试方法名称的前缀,会发生什么

NUnit也应该将其视为一种测试方法,而不必使用
TestAttribute
然而,我已经用NUnit2.4.7测试过了,这似乎不再是真的了

不管怎么说,我不明白为什么这会困扰你?使用测试属性修饰方法有什么问题?这就明确了这是一个测试。
我喜欢明确性:)

我很难理解这样做的动机。我想我可能遗漏了一些东西,但是你的[TestFixture]方法不在[TestFixture]测试类中吗?如果是这样,为什么要删除测试属性?@Russ Cam you是对的,[test]属性将位于具有TestFixture属性的类中。我的观点是,用TestFixture]属性修饰的类中的所有方法都是测试,那么为什么要显式地用[Test]属性修饰它们呢?我只是使用一个Resharper宏,通过几个按键为我创建一个测试定义,包括属性。TestFixture中的所有方法都不是测试方法。用[Test]修饰的方法是测试框架使用的入口点。您的类中可能有许多其他方法不打算由测试工具直接访问。我使用MBUnit,只是尝试了一下,但没有成功。你是对的,用[Test]属性修饰方法并不是什么大问题,但我一直在寻找一种方法来删除它默认情况下不再识别。建议您将此类测试用例转换为使用TestAttribute。或者,您可以在测试配置文件中指定一个设置,以允许默认情况下使用旧式测试用例。“请参阅,TypeDescriptor似乎只能用于添加类级别的属性。太糟糕了。它似乎有PropertyDescriptor和EventDescriptor,但没有MethodDescriptor。古怪的从另一个角度来看这个问题,你能告诉你的单元测试框架哪些类和方法是可测试的吗?如果是这样的话,您可以创建自己的方法列表并将其传入。不确定这是否可行,但这会很好:-)
[TestFixture]
    public class specifications_for_prime_test
    {
        [SetUp]
        public void initialize()
        {
            UnitTestHelper.Configure(this); 
        }
    }

    public class when_1_is_passed : specifications_for_prime_test
    {
        public void should_return_false()
        {
            Assert.AreEqual(1,1);
        }
    }