测试一个类是否有属性?

时间:2009-08-04 07:44:13

标签: c# unit-testing attributes

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

[SubControllerActionToViewDataAttribute]
public class ScheduleController : Controller

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

4 个答案:

答案 0 :(得分:115)

检查

Attribute.GetCustomAttribute(typeof(ScheduleController),
    typeof(SubControllerActionToViewDataAttribute))

不为空(Assert.IsNotNull或类似)

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

答案 1 :(得分:66)

您通常会检查某个类的属性。

以下是一些示例代码。

typeof(ScheduleController)
.IsDefined(typeof(SubControllerActionToViewDataAttribute), false);

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

答案 2 :(得分:13)

也可以使用泛型:

var type = typeof(SomeType);
var attribute = type.GetCustomAttribute<SomeAttribute>();

这样您就不需要另外typeof(...),这可以使代码更清晰。

答案 3 :(得分:6)

我知道这个帖子真的很旧,但是如果有人偶然发现它,你可能会发现fluentassertions项目非常方便进行这种断言。

typeof(MyPresentationModel).Should().BeDecoratedWith<SomeAttribute>();