Created
November 2, 2011 22:50
-
-
Save jeffhandley/1335203 to your computer and use it in GitHub Desktop.
How to validate an object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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