Пример #1
0
        /// <summary>
        /// Create a Random Value of Type
        /// </summary>
        /// <param name="objectType"></param>
        /// <returns>Random value of Type</returns>
        public static object CreateRandomValue(Type objectType)
        {
            if (objectType == typeof(Type))
            {
                return(objectType);
            }

            if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                var underlyingType = Nullable.GetUnderlyingType(objectType);
                return(RandomValueGenerator.CreateRandomValue(underlyingType));
            }

            var randomType     = objectType;
            var valueGenerator = RandomValueGenerators.FirstOrDefault(pair => pair.Key == randomType);

            if (valueGenerator.Value != null)
            {
                return(valueGenerator.Value());
            }

            if (randomType != null && randomType.IsEnum)
            {
                return(CreateRandomEnum(randomType));
            }

            if (randomType != null && randomType.IsGenericType)
            {
                if (randomType.GetGenericTypeDefinition() == typeof(IEnumerable <>) ||
                    randomType.GetGenericTypeDefinition() == typeof(IList <>) ||
                    randomType.GetGenericTypeDefinition() == typeof(List <>))
                {
                    return(CreateRandomList(randomType.GenericTypeArguments[0]));
                }

                if (randomType.GetGenericTypeDefinition() == typeof(Dictionary <,>) ||
                    randomType.GetGenericTypeDefinition() == typeof(IDictionary <,>))
                {
                    return(CreateRandomDictionary(randomType));
                }

                if (randomType.GetGenericTypeDefinition() == typeof(Collection <>) ||
                    randomType.GetGenericTypeDefinition() == typeof(ICollection <>))
                {
                    return(CreateRandomCollection(randomType.GenericTypeArguments[0]));
                }

                throw new Exception($"Generic Type Generator for {randomType.Name} does not exist");
            }

            if (randomType == null || !(randomType.IsInterface || randomType.IsClass))
            {
                throw new Exception($"Random Value Generator for {objectType.Name} does not exist");
            }

            if (randomType.IsArray && randomType.IsClass)
            {
                return(CreateRandomArray(randomType.GetElementType()));
            }

            var mockedObject = randomType.CreateSubstitute();

            return(mockedObject);
        }