Created
July 27, 2012 15:55
-
-
Save michaeljacobdavis/3188823 to your computer and use it in GitHub Desktop.
Unit testing methods for nested Fluent Validation properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Adapted from http://devio.wordpress.com/2011/01/21/get-name-of-nested-property-as-string-value/ | |
public static string GetPropertyName<T, TValue>(this T model, Expression<Func<T, TValue>> expression) where T : class | |
{ | |
var memberExpression = (MemberExpression)expression.Body; | |
var memberExpressionOrg = memberExpression; | |
var Path = ""; | |
while (memberExpression != null && memberExpression.Expression.NodeType == ExpressionType.MemberAccess) | |
{ | |
var propInfo = memberExpression.Expression.GetType().GetProperty("Member"); | |
var propValue = propInfo.GetValue(memberExpression.Expression, null) as PropertyInfo; | |
if (propValue != null) Path = propValue.Name + "." + Path; | |
memberExpression = memberExpression.Expression as MemberExpression; | |
} | |
return Path + memberExpressionOrg.Member.Name; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
target.ShouldHaveNestedValidationErrorFor(a => a.Info.EmailAddress, app); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void ShouldHaveNestedValidationErrorFor<T, TValue>(this IValidator<T> validator, Expression<Func<T, TValue>> expression, T objectToTest) where T : class | |
{ | |
var propertyName = objectToTest.GetPropertyName(expression); | |
var count = validator.Validate(objectToTest).Errors.Count(x => x.PropertyName == propertyName); | |
if (count == 0) | |
{ | |
throw new ValidationTestException(string.Format("Expected a validation error for property {0}", propertyName)); | |
} | |
} | |
public static void ShouldNotHaveNestedValidationErrorFor<T, TValue>(this IValidator<T> validator, Expression<Func<T, TValue>> expression, T objectToTest) where T : class | |
{ | |
var propertyName = objectToTest.GetPropertyName(expression); | |
var count = validator.Validate(objectToTest).Errors.Count(x => x.PropertyName == propertyName); | |
if (count > 0) | |
{ | |
throw new ValidationTestException(string.Format("Expected no validation errors for property {0}", propertyName)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment