I am using DataAnnotations for my model validation i.e.
[Required(ErrorMessage="Please enter a name")]
public string Name { get; set; }
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 ValidateModel(object model)
{
var validationResults = new List();
var ctx = new ValidationContext(model, null, null);
Validator.TryValidateObject(model, ctx, validationResults, true);
return validationResults;
}