如何测试方法参数是否用属性修饰?

2024-04-28

这可能是重复的,但我找不到我要找的问题,所以我问它。

如何测试方法参数是否用属性修饰?例如,以下 MVC 操作方法,使用 FluentValidationCustomizeValidatorAttribute:

[HttpPost]
[OutputCache(VaryByParam = "*", Duration = 1800)]
public virtual ActionResult ValidateSomeField(
    [CustomizeValidator(Properties = "SomeField")] MyViewModel model)
{
    // code
}

我确信我必须使用反射,希望使用强类型的 lambda。但不知道从哪里开始。


一旦你掌握了该方法GetMethodInfo通过反射调用,你可以简单地调用GetParameters()在该方法上,然后对于每个参数,您可以检查GetCustomAttributes()调用 X 类型的实例。例如:

Expression<Func<MyController, ActionResult>> methodExpression = 
    m => m.ValidateSomeField(null);
MethodCallExpression methodCall = (MethodCallExpression)methodExpression.Body;
MethodInfo methodInfo = methodCall.Method;

var doesTheMethodContainAttribute = methodInfo.GetParameters()
      .Any(p => p.GetCustomAttributes(false)
           .Any(a => a is CustomizeValidatorAttribute)));

Assert.IsTrue(doesTheMethodContainAttribute);

例如,此测试将告诉您是否有任何参数包含该属性。如果您想要特定参数,则需要更改GetParameters调用更具体的内容。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何测试方法参数是否用属性修饰? 的相关文章

随机推荐