How to test that a method argument is decorated with an attribute?

≯℡__Kan透↙ 提交于 2020-01-01 07:06:12

问题


This is probably a duplicate, but I can't find the question I'm looking for, so I'm asking it.

How do you test that a method argument is decorated with an attribte? For example, the following MVC action method, using FluentValidation's CustomizeValidatorAttribute:

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

I'm sure I'll have to use reflection, hopefully with strongly-typed lambdas. But not sure where to start.


回答1:


Once you get a handle on the method with a GetMethodInfo call via Reflection, you can simply call GetParameters() on that method, and then for each parameter, you can inspect the GetCustomAttributes() call for instances of type X. For example:

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);

This test, for example, would tell you if ANY of the parameters contained the attribute. If you wanted a specific parameter, you would need to change the GetParameters call into something more specific.



来源:https://stackoverflow.com/questions/10197677/how-to-test-that-a-method-argument-is-decorated-with-an-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!