xUnit检查类或方法上是否存在属性

时间:2019-05-16 23:52:50

标签: c# xunit xunit.net

xUnit是否可以测试一种方法具有特定属性?

[HttpGet]
[SwaggerOperation(OperationId = "blah", Summary = "blah", Description = "blah")]
[ProducesResponseType((int)HttpStatusCode.OK)]
public async Task<ActionResult<IList<string>>> GetSomething
(
    [Required, FromRoute(Name = "blah")] Guid aGuid,
)
{}

我希望能够测试[HttpGet]方法上是否存在GetSomething以及所有其他属性。另外,如果可能的话,还要检查[Required]属性是否在方法参数aGuid

1 个答案:

答案 0 :(得分:1)

您可以使用反射来访问属性及其数据:
Accessing Attributes by Using Reflection (C#)
Retrieving Information Stored in Attributes

但是我建议使用FluentAssertions库,该库以流利的可读性提供相同的方法。

[Fact]
public void GetAll_ShouldBeDecoratedWithHttpGetAttribute()
{
    var getSomething = nameof(_controller.GetSomething);
    typeof(MyController).GetTypeInfo()
        .GetMethod(getSomething)
        .Should()
        .BeDecoratedWith<HttpGetAttribute>();
}
相关问题