Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
XUnit test class for finding derived types that are missing an explicit public no-arg constructor
public class SomeTypeTest
{
/// <summary>
/// <remarks>A bit of a hack, but if this test fails, the last type name written to the console/debug output
/// is the one missing an explicit public no-arg constructor.</remarks>
/// </summary>
[Fact]
public void AllTypesDerivedFromSomeTypeHavePublicNoArgConstructors()
{
var type = typeof(Enumeration);
Assembly assembly = Assembly.Load("Some.Assembly.Name");
List<Type> types = assembly.GetTypes().Where(x => x.IsSubclassOf(type)).ToList();
foreach (var t in types)
{
bool printDescription = typeof(IHasDescription).IsAssignableFrom(t);
Debug.Print("Type being tested is {0}.", t.Name);
Assert.DoesNotThrow(() => t.GetConstructor(Type.EmptyTypes).Invoke(null));
Debug.Print("\tIts static properties (value:name:description) are as follows:");
foreach (var value in t.GetFields(BindingFlags.Static | BindingFlags.Public)
.Select(field => field.GetValue(null)).OfType<Enumeration>())
{
if (printDescription)
{
var descriptionProperty = GetDescriptionProperty(t);
if (descriptionProperty != null)
Debug.Print("\t{0}:{1}:{2}", value.Value, value.Name, (string)descriptionProperty.GetValue(value,null));
}
else
Debug.Print("\t({0}:{1})", value.Value, value.Name);
if (value.Attributes != null && value.Attributes.Any())
{
Debug.Print("\t\tIts attributes (description:guid) are as follows:");
foreach (var attribute in value.Attributes)
{
Debug.Print("\t\t({0}:{1})", attribute.Description, attribute.Guid);
}
Debug.Print("\r\n");
}
}
Debug.Print("\r\n");
}
}
private static PropertyInfo GetDescriptionProperty(Type t)
{
return (from prop in t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
let getAccessor = prop.GetGetMethod(true)
where getAccessor.IsFinal && getAccessor.IsPublic
select prop).FirstOrDefault();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment