Asp.net-mvc – Unit Testing ASP.NET DataAnnotations validation

asp.netasp.net-mvcdata-annotations

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

Best Answer

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;
}