caloggins
10/12/2012 - 1:04 PM

CustomArgumentValidators for FakeItEasy

CustomArgumentValidators for FakeItEasy

namespace YOUR_NAMESPACE_HERE
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using FakeItEasy;

    public static class CustomArgumentValidators
    {
        public static T HasPropertiesMatching<T>(this IArgumentConstraintManager<T> validations, object target)
        {
            return validations.Matches(source => source.PublicInstancePropertiesEqual(target));
        }

        public static bool PublicInstancePropertiesEqual<T>(this T self, T to, params string[] ignore)
            where T : class
        {
            if (self != null && to != null)
            {
                var type = typeof(T);
                var ignoreList = new List<string>(ignore);
                var unequalProperties =
                    from pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                    where !ignoreList.Contains(pi.Name)
                    let selfValue = type.GetProperty(pi.Name).GetValue(self, null)
                    let toValue = type.GetProperty(pi.Name).GetValue(to, null)
                    where selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue))
                    select selfValue;
                return !unequalProperties.Any();
            }
            return self == to;
        }
    }
}