Testing model validation without testing implementation
What's the best way of going about testing model validation开发者_JAVA技巧 without making assumptions on the implementation details of the validation (eg. DataAnnotations).
For example, if I have a Customer
model object that has a Firstname
property, I want to test that binding a missing value for the Firstname
property will result in a validation error but I don't want to test how validation his been implemented. That is, I don't want to use DataAnotations.Validate
.
I've seen several, differing, opinions on this floating around and haven't found one that I agree with.
I ended up writing a helper method that wraps ModelValidator
and returns IEnumerable<ModelValidationResult>
. It requires that MVC be configured with your validation provider of choice, but it means that test code need not change when your validation implementation does:
public static IEnumerable<ModelValidationResult> Validate<TModel>(TModel model)
{
var modelMetadata = ModelMetadata.FromLambdaExpression(r => r,
new ViewDataDictionary<TModel>(model));
ModelValidator validator = ModelValidator.GetModelValidator(
modelMetadata, new ControllerContext());
return validator.Validate(model);
}
This will depend on the framework you are using for validating your models. So what you are asking is not possible without taking this into account. ASP.NET MVC by default uses a data annotations model provider which invokes the validation rules for data annotations and if you want to test this you will need to do a DataAnnotations.Validate
in your unit tests or verify that your model is decorated with the proper attributes.
Personally I use FluentValidation.NET which provides an elegant way for unit testing my validators so it is not much of a hassle.
精彩评论