Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing ASP.NET DataAnnotations validation

I am using DataAnnotations for my model validation i.e.

[Required(ErrorMessage="Please enter a name")] public string Name { get; set; } 

In my controller, I am checking the value of ModelState. This is correctly returning false for invalid model data posted from my view.

However, when executing the unit test of my controller action, ModelState always returns true:

[TestMethod] public void Submitting_Empty_Shipping_Details_Displays_Default_View_With_Error() {     // Arrange     CartController controller = new CartController(null, null);     Cart cart = new Cart();     cart.AddItem(new Product(), 1);      // Act     var result = controller.CheckOut(cart, new ShippingDetails() { Name = "" });      // Assert     Assert.IsTrue(string.IsNullOrEmpty(result.ViewName));     Assert.IsFalse(result.ViewData.ModelState.IsValid); } 

Do I need to do anything extra to set up the model validation in my tests?

Thanks,

Ben

like image 238
Ben Foster Avatar asked Jan 30 '10 12:01

Ben Foster


People also ask

What is the use of using system ComponentModel DataAnnotations?

Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.

What is DataAnnotations MVC?

DataAnnotations is used to configure your model classes, which will highlight the most commonly needed configurations. DataAnnotations are also understood by a number of . NET applications, such as ASP.NET MVC, which allows these applications to leverage the same annotations for client-side validations.


1 Answers

I posted this in my blog post:

using System.ComponentModel.DataAnnotations;  // model class public class Fiz {     [Required]     public string Name { get; set; }      [Required]     [RegularExpression(".+@..+")]     public string Email { get; set; } }  // in test class [TestMethod] public void EmailRequired() {     var fiz = new Fiz          {             Name = "asdf",             Email = null         };     Assert.IsTrue(ValidateModel(fiz).Any(         v => v.MemberNames.Contains("Email") &&               v.ErrorMessage.Contains("required"))); }  private IList<ValidationResult> ValidateModel(object model) {     var validationResults = new List<ValidationResult>();     var ctx = new ValidationContext(model, null, null);     Validator.TryValidateObject(model, ctx, validationResults, true);     return validationResults; } 
like image 145
Jon Davis Avatar answered Oct 19 '22 07:10

Jon Davis