奥秘:我的自定义c#属性只使用一次,但在运行单元测试时构造了多次.为什么

本文关键字:运行 单元测试 为什么 一次 自定义 我的 属性 奥秘 | 更新日期: 2023-09-27 18:15:57

我有一个谜,我似乎无法解决。我有这个非常简单的单元测试,它使用了一个非常简单的自定义属性。该属性只被添加到一个甚至没有实例化的类中。我计算构造属性的次数。我希望一次,因为属性放在类MyDummyClass上。但由于某种原因,单位测试的结果是2。如果我把它加到类中两次,结果是4。如果我将它添加到MyTestClass中,它将增加6,如果我将它添加到MyTest中,则会增加13。因此,在MyDummyClass、MyTestClass和MyTest上拥有该属性的结果是计数为21。为什么! ?

我做了一些额外的测试:
-如果我在控制台应用程序中尝试此操作,它会按预期工作并导致1.
-如果我在MsTest项目中这样做,并使用VS MsTest运行器,结果是1。
如果我在NUnit自己的查看器(2.0框架)或resharper中运行代码,它是21。
-值得注意的是:如果我用resharper运行MsTest测试,结果是2。看来resharper也搞砸了一些东西。

我正在使用VS2010 build 10.0.40219.1, Resharper v6.1.1000.82和NUnit 2.5.10(由r#提供)

想测试一下吗?继续,下面是代码:

using System;
using NUnit.Framework;
namespace MyTests
{
    [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
    public class WtfAttribute : Attribute
    {
        public static int CallCount = 0;
        public WtfAttribute() //every time the attribute is constructed the count is incremented by 1.
        {
            CallCount++;
        }
    }
    //this class is NEVER instantiated, but adding the attribute to it increases the callcount by 2. I expected it to be 1 due to reflection.
    [Wtf]
    public class MyDummyClass
    {
    }
    [TestFixture]
    //adding the attribute to MyTestClass increases the callcount by 6.
    //[Wtf]
    public class MyTestClass
    {
        [Test]
        //adding the attribute to MyTest increases the callcount by 13.
        //[Wtf]
        public void MyTest()
        {
            Assert.AreEqual(1, WtfAttribute.CallCount, "CallCount = " + WtfAttribute.CallCount);
        }
    }
}

我希望有人能帮我弄清楚到底是怎么回事。为什么CallCount不是1?感谢您提供的任何帮助和意见。

问候,Ted

奥秘:我的自定义c#属性只使用一次,但在运行单元测试时构造了多次.为什么

原因是单元测试框架使用反射检查您的程序集,并且它们查询所有程序集、类型和方法的自定义属性。

当你这样做时(即调用GetCustomAttributes()),属性被构造,以便它们可以在该调用的结果中返回。

我猜单元测试框架正在做这种类型的反射多次