gpt4 book ai didi

c# - 神秘 : my custom C# attribute is used once, 但在运行单元测试时构造了无数次。为什么?

转载 作者:行者123 更新时间:2023-11-30 14:59:25 27 4
gpt4 key购买 nike

我有一个似乎无法解开的谜。我有这个非常简单的单元测试,它使用了一个非常简单的自定义属性。该属性仅添加到甚至未实例化的 1 个类。我计算属性被构建的次数。由于类 MyDummyClass 上的属性,我希望有一次。但由于某种原因,unittest 结果为 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);
}
}
}

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

问候,泰德

最佳答案

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

当您执行此操作(即调用 GetCustomAttributes())时,将构造属性以便它们可以在该调用的结果中返回。

我猜单元测试框架会多次进行这种类型的反射。

关于c# - 神秘 : my custom C# attribute is used once, 但在运行单元测试时构造了无数次。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16814533/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com