【问题标题】:How to test that a method argument is decorated with an attribute?如何测试方法参数是否用属性修饰?
【发布时间】:2012-04-29 04:09:21
【问题描述】:

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

如何测试方法参数是否用属性修饰?比如下面的MVC动作方法,使用FluentValidation的CustomizeValidatorAttribute

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

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

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 unit-testing asp.net-mvc-4 custom-attributes


    【解决方案1】:

    一旦通过反射获得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 调用更改为更具体的参数。

    【讨论】:

    • 感谢您的快速回答。我编辑了问题以提供获取 MethodInfo 的示例代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2010-09-06
    • 2015-07-23
    相关资源
    最近更新 更多