using System; using NUnit.Framework; namespace AgileKiwi.SimpleValidation.Tests { /// /// A class to run some validation on, complete with validation rules /// public class Animal { public Animal(string name, int numberOfLegs) { _animalName = name; _numberOfLegs = numberOfLegs; } string _animalName; int _numberOfLegs; public string AnimalName { get { return _animalName; } set { _animalName = value; } } public int NumberOfLegs { get { return _numberOfLegs; } set { _numberOfLegs = value; } } [Validate] protected Result NumberOfLegsMustBeEven() { return NumberOfLegs % 2 == 0; } [Validate] protected Result MythicalSpeciesAreNotAllowed() { if (AnimalName == "Unicorn" || AnimalName == "Dragon") return Validation.Error("'" + AnimalName + "' is not a real species"); else return Validation.NotApplicable; } [Validate] protected Result NumberOfLegsMustBePlausible() { return NumberOfLegs <= 10 || Validation.Error("Your '" + AnimalName + "' has too many legs"); } } [TestFixture] public class SimpleValidationTests { Animal animalThatFailsAllRules = new Animal("Unicorn", 11); Animal animalThatPassesAllRules = new Animal("Cat", 4); [Test] public void CanCallUsingTypedValidator() { foreach(Result r in Validator.ExecuteRulesOn(animalThatPassesAllRules)) if(!r.Pass) Assert.Fail("No failures expected"); int count = 0; foreach (Result r in Validator.ExecuteRulesOn(animalThatFailsAllRules)) if(!r.Pass) count++; Assert.AreEqual(3, count); } [Test] public void CanCallUsingUnTypedValidator() { Validator v = Validator.GetInstanceFor(typeof(Animal)); foreach (Result r in v.ExecuteRulesOn(animalThatPassesAllRules)) if (!r.Pass) Assert.Fail("No failures expected"); int count = 0; foreach (Result r in v.ExecuteRulesOn(animalThatFailsAllRules)) if (!r.Pass) count++; Assert.AreEqual(3, count); } [Test] public void CanGetResultFromMethodName() { Animal a = new Animal("Dog", 3); // construct an test animalthat fails only the rule we want to test foreach (Result r in Validator.ExecuteRulesOn(a)) if(!r.Pass) Assert.AreEqual("Number of legs must be even", r.FailureMessage); // this is based on the method name } [Test] public void CanGetResultFromExplicitReturn() { Animal a = new Animal("Dragon", 4); // construct an test animalthat fails only the rule we want to test foreach (Result r in Validator.ExecuteRulesOn(a)) if (!r.Pass) Assert.AreEqual("'Dragon' is not a real species", r.FailureMessage); // this is not based on the method name } [Test] public void CanGetResultFromORedReturn() { Animal a = new Animal("Cow", 12); // construct an test animalthat fails only the rule we want to test foreach (Result r in Validator.ExecuteRulesOn(a)) if (!r.Pass) Assert.AreEqual("Your 'Cow' has too many legs", r.FailureMessage); // returned by our || syntax } } }