I am trying to initialize objects for tests purposes. After initializing an object, I want to assert that all properties whose underlying type is a value type have a value that is not the default value of the property's type, with certain exceptions. I am not trying to recurse into sub-objects. For this purpose, I have the following:
public static void NoValueTypedPropertyHasDefaultValue<T>(this T t, params string[] exceptions)
where T: class
{
foreach (var property in typeof(T).GetProperties())
{
var propertyType = property.PropertyType;
if (propertyType.IsValueType && !exceptions.Any(x => x == property.Name))
{
var defaultValue = Activator.CreateInstance(propertyType);
object actualValue = property.GetValue(t);
Assert.NotEqual(defaultValue, actualValue);
}
}
}
Provided that everything has a parameterless constructor, it works. I'm not thrilled with the way I'm passing in strings for the exceptions. Is there a better way to do that?
Aucun commentaire:
Enregistrer un commentaire