Unit Testing of MVC5 Validation with Foolproof - NotImplemented Exception

360 views Asked by At

I am doing unit testing of my validation logic in MVC using the following helper method:

public static void ValidateViewModel(Controller controller, object viewModelToValidate)
{
    var validationContext = new ValidationContext(viewModelToValidate, null, null);
    var validationResults = new List<ValidationResult>();
    Validator.TryValidateObject(viewModelToValidate, validationContext, validationResults, true);
    foreach (var validationResult in validationResults)
    {
        controller.ModelState.AddModelError(validationResult.MemberNames.FirstOrDefault() ?? string.Empty, validationResult.ErrorMessage);
    }
}

One of my data models contains the following:

[NotMapped]
public string ValidSignupCode { get { return "VALID_SIGNUP_CODE"; } }

[MaxLength(15)]
[EqualTo("ValidSignupCode", ErrorMessage = "Sign up Code is not valid.")]
public string SignupCode { get; set; }

This throws a NotImplementedException from Foolproof with this stacktrace:

   at Foolproof.ModelAwareValidationAttribute.IsValid(Object value)
   at System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(Object value, ValidationContext validationContext)
   at System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(Object value, ValidationContext validationContext)
   at System.ComponentModel.DataAnnotations.Validator.TryValidate(Object value, ValidationContext validationContext, ValidationAttribute attribute, ValidationError& validationError)
   at System.ComponentModel.DataAnnotations.Validator.GetValidationErrors(Object value, ValidationContext validationContext, IEnumerable`1 attributes, Boolean breakOnFirstError)
   at System.ComponentModel.DataAnnotations.Validator.GetObjectPropertyValidationErrors(Object instance, ValidationContext validationContext, Boolean validateAllProperties, Boolean breakOnFirstError)
   at System.ComponentModel.DataAnnotations.Validator.GetObjectValidationErrors(Object instance, ValidationContext validationContext, Boolean validateAllProperties, Boolean breakOnFirstError)
   at System.ComponentModel.DataAnnotations.Validator.TryValidateObject(Object instance, ValidationContext validationContext, ICollection`1 validationResults, Boolean validateAllProperties)

The interesting thing is that this runs fine when running MVC, but not in UnitTest land.

My goal is to unit test validations and bindings through the MVC interface in order to ensure changes don't have far reaching effects as the project gets bigger.

Any advice on ways to get this to work are greatly appreciated.

1

There are 1 answers

0
Martin Noreke On

I ended up downloading the Foolproof code from Codeplex to dig into this one.

public override bool IsValid(object value)
{
    throw new NotImplementedException();
}

The validation method being called isn't implemented. I'll reach out on their message boards to see how to get this resolved instead.