/// <summary> /// Adds a random value to a property. /// </summary> /// <typeparam name="T">Type to add the property value to.</typeparam> /// <param name="obj">Object to add the property value to.</param> /// <param name="property">Property to add the value to.</param> public static void PopulatePropertyWithRandomValue<T>(T obj, PropertyInfo property) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } else if (property == null) { throw new ArgumentNullException(nameof(obj)); } if (PropertyUtilities.CheckIfPropertyIsList(property) || PropertyUtilities.CheckIfPropertyIsClass(property)) { if (obj.GetType() == property.PropertyType) { throw new ArgumentException($"The property {property.Name} is trying to add the type {property.PropertyType}, which is the same type.", nameof(property)); } if (PropertyUtilities.CheckIfPropertyIsReadWrite(property)) { property.SetValue(obj, Activator.CreateInstance(property.PropertyType)); } PopulateObjectWithRandomValues(property.GetValue(obj)); return; } if (!PropertyUtilities.CheckIfPropertyIsReadWrite(property)) { return; } switch (property.PropertyType) { case Type t when t == typeof(string): property.SetValue(obj, RandomUtilities.GetRandomString((string)property.GetValue(obj))); break; case Type t when t.IsEnum: property.SetValue(obj, RandomUtilities.GetRandomEnum((Enum)property.GetValue(obj))); break; case Type t when t == typeof(bool): property.SetValue(obj, RandomUtilities.GetRandomBoolean((bool)property.GetValue(obj))); break; case Type t when t == typeof(int): property.SetValue(obj, RandomUtilities.GetRandomInteger((int)property.GetValue(obj))); break; case Type t when t == typeof(DateTime): property.SetValue(obj, RandomUtilities.GetRandomDateTime((DateTime)property.GetValue(obj))); break; case Type t when t == typeof(double): property.SetValue(obj, RandomUtilities.GetRandomDouble((double)property.GetValue(obj))); break; case Type t when t == typeof(decimal): property.SetValue(obj, RandomUtilities.GetRandomDecimal((decimal)property.GetValue(obj))); break; default: throw new ArgumentException($"The property {property.Name} uses an unsupported value type of {property.PropertyType} for this method.", nameof(property)); } }
/// <summary> /// Tests that a specific property of an object changes values. /// </summary> /// <typeparam name="T">Type of object to test.</typeparam> /// <param name="obj">Object with property to test.</param> /// <param name="property">Property to test.</param> public static void ChangesValue <T>(T obj, PropertyInfo property) { for (int i = 0; i < new Random().Next(5, 20); i++) { var randomObject = ObjectUtilities.CreateInstanceWithRandomValues(obj.GetType()); property.SetValue(obj, property.GetValue(randomObject)); Assert.AreEqual(property.GetValue(randomObject), property.GetValue(obj)); } if (PropertyUtilities.CheckIfPropertyIsClass(property)) { ChangesValues(property.GetValue(obj)); } }