C# 测试一个类是否有一个属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1226161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 13:54:22  来源:igfitidea点击:

Test if a class has an attribute?

c#unit-testingattributes

提问by JoshRivers

I'm trying to do a little Test-First development, and I'm trying to verify that my classes are marked with an attribute:

我正在尝试进行一些测试优先开发,并尝试验证我的类是否标有属性:

[SubControllerActionToViewDataAttribute]
public class ScheduleController : Controller

How do I unit test that the class has that attribute assigned to it?

我如何单元测试该类是否具有分配给它的属性?

采纳答案by Marc Gravell

check that

检查一下

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

isn't null (Assert.IsNotNullor similar)

不为空(Assert.IsNotNull或类似的)

(the reason I use this rather than IsDefinedis that most times I want to validate some properties of the attribute too....)

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

回答by RichardOD

The same you would normally check for an attribute on a class.

与您通常检查类的属性相同。

Here's some sample code.

这是一些示例代码。

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

I think in many cases testing for the existence of an attribute in a unit test is wrong. As I've not used MVC contrib's sub controller functionality I can't comment whether it is appropriate in this case though.

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

回答by Aleksey L.

I know this thread is really old, but if somebody stumble upon on it you may find fluentassertionsproject very convenient for doing this kind of assertions.

我知道这个线程真的很老,但是如果有人偶然发现它,您可能会发现fluentassertions项目对于执行此类断言非常方便。

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

回答by Kroltan

It is also possible to use generics on this:

也可以在此使用泛型:

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

This way you do not need another typeof(...), which can make the code cleaner.

这样你就不需要另一个typeof(...),这可以使代码更干净。