asp.net-mvc - 如何测试方法参数是否用属性修饰?

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

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

如何测试方法参数是否用属性修饰?例如,以下 MVC 操作方法,使用 FluentValidation 的 CustomizeValidatorAttribute:

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

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

最佳答案

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

关于asp.net-mvc - 如何测试方法参数是否用属性修饰?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10197677/

相关文章:

javascript - asp.net MVC 路由 - javascript url 404 错误

c# - 一个类中的测试是否保证不会同时执行?

c# - 找不到类型或命名空间名称 'TwilioRestClient'

asp.net-mvc - 带有 Bootstrap 分页的 Asp.NET WebGrid

asp.net-mvc - Upshot/Knockout 架构最佳实践 - 在 Upshot 和 .NET 之间通信时使用的首选提供程序是什么?

asp.net-mvc-3 - MVC 2/MVC 3/MVC 4中的嵌套区域

asp.net-mvc - 在 ASP.NET MVC 中设置备用 Controller 文件夹位置

jquery - 如何让jquery文件上传回发除[httpPost]index.cshtml()之外的指定操作?

Python 使用部分测试属性

oracle - PL/SQL的单元测试