Thursday, 6 March 2014

Validating Model with Data Annotations in Unit Test

We could use the classes inside System.ComponentModel.DataAnnotations to help us in testing model with data annotations.

First, include the assembly in the test project reference libraries.

Then we can use this method of Validator class to do the validation, along with a ValidationContext instance and a collection of ValidationResult type as parameters.
public static bool TryValidateObject(
 Object instance,
 ValidationContext validationContext,
 ICollection<ValidationResult> validationResults,
 bool validateAllProperties
)
We need to pass a validation context instance, a collection to hold the result of each failed validation and a boolean value to indicate whether to validate all properties that are decorated with data annotations or only properties that are decorated with [Required] attribute only. To create a new instance of validation context, we could simply pass the object to be validated into ValidationContext() constructor method:
ValidationContext context = new ValidationContext(object_to_be_validated);

Below is a full example:
List<ValidationResult> validationResults = null;
var itemSellingDto = new ItemSellingDto() { InvoiceId = 0, ItemId = 1, ItemName = "", ItemSellingId = 0, Price = 0, Quantity = 10 };
var validationContext = new ValidationContext(itemSellingDto);

var isValid = Validator.TryValidateObject(itemSellingDto, validationContext, validationResults, validateAllProperties: true);

isValid.should_be(false);
validationResults.Any(vr => vr.ErrorMessage == "Price must be bigger than 0").should_be(true);


No comments: