Skip to content

Instantly share code, notes, and snippets.

@jeroenheijmans
Created March 20, 2016 14:37
Show Gist options
  • Save jeroenheijmans/802c2e6ce4bc1b0edf24 to your computer and use it in GitHub Desktop.
Save jeroenheijmans/802c2e6ce4bc1b0edf24 to your computer and use it in GitHub Desktop.
All Collection properties should be instantiated for types with empty constructors
using NUnit.Framework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace MyProject.Dto.Tests
{
[TestFixture]
public class DtoTests
{
[Test]
public void NamespaceDtos_WhenDefaultConstructorIsCalled_InstantiatesCollectionProperties()
{
bool testWasMeaningful = false;
foreach (var type in GetEntityTypesWithDefaultConstructor())
{
var instance = Activator.CreateInstance(type);
var collectionProps = type
.GetProperties()
.Where(p => IsOrImplementsICollection(p.PropertyType));
foreach (var prop in collectionProps)
{
var val = prop.GetValue(instance);
Assert.That(val, Is.Not.Null.And.Empty, string.Format("[{0}.{1}]", type.Name, prop.Name));
testWasMeaningful = true;
}
}
Assert.That(testWasMeaningful, "Expected at least one assertion.");
}
private IEnumerable<Type> GetEntityTypesWithDefaultConstructor()
{
return Assembly
.GetAssembly(typeof(MyProject.Dto.Things.Item))
.GetTypes()
.Where(t => !t.IsAbstract)
.Where(t => t.GetConstructor(Type.EmptyTypes) != null);
}
private static bool IsOrImplementsICollection(Type t)
{
if (t == typeof(ICollection)) return true;
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ICollection<>)) return true;
return t.GetInterfaces().Any(IsOrImplementsICollection);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment