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
大多数时候我想验证属性的某些属性......)
Ric*_*dOD 73
您通常会检查类的属性.
这是一些示例代码.
typeof(ScheduleController)
.IsDefined(typeof(SubControllerActionToViewDataAttribute), false);
Run Code Online (Sandbox Code Playgroud)
我认为在许多情况下测试单元测试中是否存在属性是错误的.由于我没有使用MVC contrib的子控制器功能,我无法评论它是否适合这种情况.
Kro*_*tan 14
也可以在此使用泛型:
var type = typeof(SomeType);
var attribute = type.GetCustomAttribute<SomeAttribute>();
Run Code Online (Sandbox Code Playgroud)
这样你就不需要另一个了typeof(...)
,这可以使代码更清晰.
我知道这个线程真的很老,但如果有人偶然发现它你可能会发现fluentassertions项目非常方便做这种断言.
typeof(MyPresentationModel).Should().BeDecoratedWith<SomeAttribute>();
Run Code Online (Sandbox Code Playgroud)