How to test that a method argument is decorated wi

2020-06-25 06:56发布

问题:

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.