首页 > 解决方案 > xUnit 检查类或方法上是否存在属性

问题描述

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

标签: c#xunitxunit.net

解决方案


您可以使用反射访问属性及其数据:使用反射
访问属性 (C#)
检索存储在属性中的信息

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

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

推荐阅读