Skip to content

Instantly share code, notes, and snippets.

@jeffhandley
Created November 2, 2011 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffhandley/1335203 to your computer and use it in GitHub Desktop.
Save jeffhandley/1335203 to your computer and use it in GitHub Desktop.
How to validate an object
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace QuickTests
{
[TestClass]
public class SingerTests
{
public class Singer
{
[Required, StringLength(20)]
public string FirstName { get; set; }
[Required, StringLength(20)]
public string LastName { get; set; }
}
[TestMethod]
public void RequiredFieldsValidatedFirst()
{
var cher = new Singer { FirstName = "The artist formerly known as" };
var vc = new ValidationContext(cher, null, null);
var results = new List<ValidationResult>();
// Ensure required fields are met and object-level validation is valid
var isValid = Validator.TryValidateObject(cher, vc, results);
Assert.IsFalse(isValid);
Assert.AreEqual(1, results.Count);
}
[TestMethod]
public void PropertyValuesNotValidatedByDefault()
{
var cher = new Singer { FirstName = "The artist formerly known as", LastName = "Prince" };
var vc = new ValidationContext(cher, null, null);
var results = new List<ValidationResult>();
// By default, property values are not validated, as they were most-likely validated
// while being set.
var isValid = Validator.TryValidateObject(cher, vc, results);
Assert.IsTrue(isValid);
Assert.AreEqual(0, results.Count);
}
[TestMethod]
public void PropertyValuesCanBeValidatedToo()
{
var cher = new Singer { FirstName = "The artist formerly known as", LastName = "Prince" };
var vc = new ValidationContext(cher, null, null);
var results = new List<ValidationResult>();
// By default, property values are not validated, as they were most-likely validated
// while being set. But you can force property value validation too.
var isValid = Validator.TryValidateObject(cher, vc, results, validateAllProperties: true);
Assert.IsFalse(isValid);
Assert.AreEqual(1, results.Count);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment