2

這可能是重複的,但我找不到我正在尋找的問題,所以我在問它。如何測試一個方法參數是用一個屬性裝飾的?

你如何測試方法參數是用attribte裝飾的?例如,下面的MVC操作方法,使用FluentValidation的CustomizeValidatorAttribute

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

我敢肯定,我不得不強類型的lambda表達式使用反射,希望。但不知道從哪裏開始。

回答

3

一旦你瞭解了通過反射一個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調用更改爲更具體的調用。

+0

感謝您的快速回答。我編輯了這個問題以提供獲取MethodInfo的示例代碼。 – danludwig 2012-04-18 02:45:09

相關問題