private static object ConstructNewType(Type type) { var constructors = type.GetConstructors(); var constructorWithMostParameters = constructors.FirstOrDefault(x => x.GetParameters().Count() == constructors.Min(y => y.GetParameters().Count())); if (constructorWithMostParameters == null) { throw new Exception($"Could not find constructor to construct type {type.Name}"); } var constructorParameters = constructorWithMostParameters.GetParameters(); var parameters = new object[constructorParameters.Count()]; for (int i = 0; i < parameters.Count(); i++) { parameters[i] = ObjectGeneratorExtensions.GetRandomValue(constructorParameters[i].ParameterType); } return(constructorWithMostParameters.Invoke(parameters)); }
public static object Generate(Type type, Func <object> constructor = null, bool useNullOnUnknownType = true, string[] ignoreProperties = null) { if (constructor == null) { constructor = () => ConstructNewType(type); } var obj = constructor.Invoke(); var allProperties = obj.GetType().GetProperties(); if (ignoreProperties != null) { allProperties = allProperties.Where(p => !ignoreProperties.Contains(p.Name)).ToArray(); } foreach (var propertyInfo in allProperties) { ObjectGeneratorExtensions.SetValueOnProperty(obj, propertyInfo, useNullOnUnknownType); } return(obj); }