// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; namespace Microsoft.TestCommon { public abstract class EnumHelperTestBase where TEnum : IComparable, IFormattable, IConvertible { private Func _isDefined; private Action _validate; private TEnum _undefined; /// /// Helper to verify that we validate enums correctly when passed as arguments etc. /// /// A Func used to validate that a value is defined. /// A Func used to validate that a value is definded of throw an exception. /// An undefined value. protected EnumHelperTestBase(Func isDefined, Action validate, TEnum undefined) { _isDefined = isDefined; _validate = validate; _undefined = undefined; } [Fact] public void IsDefined_ReturnsTrueForDefinedValues() { Array values = Enum.GetValues(typeof(TEnum)); foreach (object value in values) { if (ValueExistsForFramework((TEnum)value)) { Assert.True(_isDefined((TEnum)value)); } else { Assert.False(_isDefined((TEnum)value)); } } } [Fact] public void IsDefined_ReturnsFalseForUndefinedValues() { Assert.False(_isDefined(_undefined)); } [Fact] public void Validate_DoesNotThrowForDefinedValues() { Array values = Enum.GetValues(typeof(TEnum)); foreach (object value in values) { if (ValueExistsForFramework((TEnum)value)) { _validate((TEnum)value, "parameter"); } } } [Fact] public void Validate_ThrowsForUndefinedValues() { AssertForUndefinedValue( () => _validate(_undefined, "parameter"), "parameter", (int)Convert.ChangeType(_undefined, typeof(int)), typeof(TEnum), allowDerivedExceptions: false); } /// /// Override this if InvalidEnumArgument is not supported in the targetted platform /// /// A delegate to the code to be tested /// The name of the parameter that should throw the exception /// The expected invalid value that should appear in the message /// The type of the enumeration /// Pass true to allow exceptions which derive from TException; pass false, otherwise protected virtual void AssertForUndefinedValue(Action testCode, string parameterName, int invalidValue, Type enumType, bool allowDerivedExceptions = false) { Assert.ThrowsInvalidEnumArgument( testCode, parameterName, invalidValue, enumType, allowDerivedExceptions); } /// /// Override this to determine if a given enum value for an enum exists in a given framework /// /// /// Wheter the value exists protected virtual bool ValueExistsForFramework(TEnum value) { return true; } } }