Skip to content

Instantly share code, notes, and snippets.

@michaeljacobdavis
Created July 27, 2012 15:55
Show Gist options
  • Save michaeljacobdavis/3188823 to your computer and use it in GitHub Desktop.
Save michaeljacobdavis/3188823 to your computer and use it in GitHub Desktop.
Unit testing methods for nested Fluent Validation properties
// 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;
}
target.ShouldHaveNestedValidationErrorFor(a => a.Info.EmailAddress, app);
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