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

烂漫一生 提交于 2019-12-03 22:15:41
Tejs

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.

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