Ted*_*Net 3 c# reflection attributes nunit mstest
我有一个我似乎无法解决的谜。我有一个使用非常简单的自定义属性的非常简单的单元测试。该属性仅添加到一个甚至没有实例化的类。我计算构造属性的次数。由于类MyDummyClass的属性,我期望一次。但是由于某种原因,单元测试的结果为2。如果将它两次添加到类中,则结果为4。如果将其添加到MyTestClass,则结果将增加6;如果将其添加到MyTest,则将发生13的增加。因此,具有MyDummyClass,MyTestClass和MyTest的属性的计数为21。
我做了一些额外的测试:
-如果在控制台应用程序中尝试此操作,它将按预期工作并得到
1。-如果我在MsTest项目中进行此操作并使用VS MsTest
运行器,则结果为1。- 如果运行在NUnit自己的查看器(2.0框架)中或在具有
reshaper的情况下,该代码为21。-值得注意的是:如果我以reshaper运行MsTest测试,结果为2。
我正在使用VS2010版本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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望任何人都可以帮助我弄清楚WTF正在进行的事情。为什么没有CallCount 1?感谢您提供的任何帮助和意见。
问候,泰德
原因是单元测试框架使用反射检查您的程序集,并且它们查询所有程序集,类型和方法上的自定义属性。
当您执行此操作(即call GetCustomAttributes())时,将构造属性,以便可以在该调用的结果中返回它们。
我猜单元测试框架会多次执行这种类型的反射。