c# - 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#)
检索存储在属性中的信息
但我建议使用FluentAssertions库,它以流利的可读方式提供相同的方法。
[Fact]
public void GetAll_ShouldBeDecoratedWithHttpGetAttribute()
{
var getSomething = nameof(_controller.GetSomething);
typeof(MyController).GetTypeInfo()
.GetMethod(getSomething)
.Should()
.BeDecoratedWith<HttpGetAttribute>();
}
推荐阅读
- python - 在 Python 中多次创建海龟对象
- python-3.x - 从 SSH 未从字节解码为 ASCII?
- objective-c - 与Objective C等效的stringFromCharCode?
- sql - SQL Server 以小时为单位的时间差为整数
- python - Plotly 3D 散点图在 Google Colab 中的窗口大小非常小
- amazon-redshift - Redshift COPY 命令需要很长时间
- python - psutil.disk_usage('/') 返回奇怪的值
- pandas - 数据有什么问题??尽管有值但不显示正确的标签,但显示 NaN 值
- vba - 使用自动化/VBA 填充 Excel 时,Access O365 崩溃
- c# - 在 ASP.NET Core 3.1 中使用多个身份验证方案?