测试一个类是否有属性?

Jos*_*ers 95 c# attributes unit-testing

我正在尝试进行一些Test-First开发,我正在尝试验证我的类是否标有属性:

[SubControllerActionToViewDataAttribute]
public class ScheduleController : Controller
Run Code Online (Sandbox Code Playgroud)

如何对该类具有分配给它的属性进行单元测试?

Mar*_*ell 118

检查一下

Attribute.GetCustomAttribute(typeof(ScheduleController),
    typeof(SubControllerActionToViewDataAttribute))
Run Code Online (Sandbox Code Playgroud)

不是null(Assert.IsNotNull或类似)

(我之所以使用它而不是IsDefined大多数时候我想验证属性的某些属性......)

  • 为了检查属性是否存在,这通常是无参数/无属性属性所需要的,使用它更便宜.IsDefined,因为它将查询元数据,而不是反序列化和实例化属性对象. (5认同)

Ric*_*dOD 73

您通常会检查类的属性.

这是一些示例代码.

typeof(ScheduleController)
.IsDefined(typeof(SubControllerActionToViewDataAttribute), false);
Run Code Online (Sandbox Code Playgroud)

我认为在许多情况下测试单元测试中是否存在属性是错误的.由于我没有使用MVC contrib的子控制器功能,我无法评论它是否适合这种情况.

  • 这种方法比以前更快 (9认同)

Kro*_*tan 14

也可以在此使用泛型:

var type = typeof(SomeType);
var attribute = type.GetCustomAttribute<SomeAttribute>();
Run Code Online (Sandbox Code Playgroud)

这样你就不需要另一个了typeof(...),这可以使代码更清晰.

  • 好的,[此处](https://msdn.microsoft.com/it-it/library/hh194292(v=vs.110).aspx) 我发现 `GetCustomAttribute&lt;SomeAttribute&gt;` 方法可从 .NET 4.5 中获取,并且我的 IDE 设置为 3.5,所以现在一切都清楚了 (2认同)

Ale*_* L. 8

我知道这个线程真的很老,但如果有人偶然发现它你可能会发现fluentassertions项目非常方便做这种断言.

typeof(MyPresentationModel).Should().BeDecoratedWith<SomeAttribute>();
Run Code Online (Sandbox Code Playgroud)