我试图做一个小测试优先发展,我想验证我的课标有一个属性:测试一个类是否有属性?
[SubControllerActionToViewDataAttribute]
public class ScheduleController : Controller
我如何单元测试类已经分配了属性到它?
我试图做一个小测试优先发展,我想验证我的课标有一个属性:测试一个类是否有属性?
[SubControllerActionToViewDataAttribute]
public class ScheduleController : Controller
我如何单元测试类已经分配了属性到它?
检查
Attribute.GetCustomAttribute(typeof(ScheduleController),
typeof(SubControllerActionToViewDataAttribute))
不为空(Assert.IsNotNull
或类似)
(我用这个,而不是IsDefined
的原因是,大多数时候,我要验证的属性的一些性质了。 ...)
同样你通常会检查一个类的属性。
下面是一些示例代码。
typeof(ScheduleController)
.IsDefined(typeof(SubControllerActionToViewDataAttribute), false);
我认为在很多情况下,单元测试中存在属性的测试是错误的。由于我没有使用MVC contrib的子控制器功能,我不能评论它是否适合这种情况。
我知道这个线程真的很老,但如果有人偶然发现它,您可能会发现fluentassertions项目对于做这种断言非常方便。
typeof(MyPresentationModel).Should().BeDecoratedWith<SomeAttribute>();
也可能就此使用泛型:
var type = typeof(SomeType);
var attribute = type.GetCustomAttribute<SomeAttribute>();
这样,你不需要再typeof(...)
,它可以使代码更干净。
做了+1然后发现错误。它应该是.IsDefined(typeof(Type),false); – 2012-04-05 13:13:04
@alexanderb你当然是对的。我已经更新了我的答案。我当时不必在编译器上检查我的答案!感谢您指出错误 – RichardOD 2012-06-23 16:05:49
这种方法比之前的 – Slava 2014-07-18 12:11:49