【发布时间】:2018-06-05 20:44:11
【问题描述】:
我正在尝试进行一些测试优先开发,并且正在尝试验证我的类是否标有属性:
[SubControllerActionToViewDataAttribute]
public class ScheduleController : Controller
我如何对类分配了该属性进行单元测试?
【问题讨论】:
标签: c# unit-testing attributes
我正在尝试进行一些测试优先开发,并且正在尝试验证我的类是否标有属性:
[SubControllerActionToViewDataAttribute]
public class ScheduleController : Controller
我如何对类分配了该属性进行单元测试?
【问题讨论】:
标签: c# unit-testing attributes
检查一下
Attribute.GetCustomAttribute(typeof(ScheduleController),
typeof(SubControllerActionToViewDataAttribute))
不为空(Assert.IsNotNull 或类似)
(我使用这个而不是IsDefined 的原因是大多数时候我也想验证属性的某些属性......)
【讨论】:
您通常会检查类的属性。
这里有一些示例代码。
typeof(ScheduleController)
.IsDefined(typeof(SubControllerActionToViewDataAttribute), false);
我认为在许多情况下,在单元测试中测试属性是否存在是错误的。由于我没有使用 MVC contrib 的子控制器功能,我无法评论它在这种情况下是否合适。
【讨论】:
也可以在这个上使用泛型:
var type = typeof(SomeType);
var attribute = type.GetCustomAttribute<SomeAttribute>();
这样你就不需要另一个typeof(...),这样可以让代码更干净。
【讨论】:
using ..?
using)你得到什么错误?
GetCustomAttribute<SomeAttribute> 方法适用于 .NET 4.5,我的 IDE 设置为 3.5,所以现在一切都清楚了
我知道这个帖子很老了,但如果有人偶然发现它,你可能会发现 fluentassertions 项目非常适合做这种断言。
typeof(MyPresentationModel).Should().BeDecoratedWith<SomeAttribute>();
【讨论】: