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
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With