如何测试一个方法参数装饰有一个属性? [英] How to test that a method argument is decorated with an attribute?

查看:106
本文介绍了如何测试一个方法参数装饰有一个属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

你怎么测试方法的参数装饰着attribte?例如,下面的MVC的操作方法,使用FluentValidation的 CustomizeValidatorAttribute

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
}

我敢肯定,我将不得不使用反射,希望与强类型的lambda表达式。但不知道从哪里开始。

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

推荐答案

一旦你得到通过思考a GetMethodInfo 调用该方法的手柄,你可以简单地调用 GetParameters()上的方法,然后对每个参数,您可以检查 GetCustomAttributes()呼吁类型的实例十,例如:

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

本试验,例如,如果将任何参数包含的属性告诉你。如果你想要一个特定参数,您将需要修改 GetParameters 呼吁为更具体的东西。

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.

这篇关于如何测试一个方法参数装饰有一个属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆