Created
March 20, 2016 14:37
-
-
Save jeroenheijmans/802c2e6ce4bc1b0edf24 to your computer and use it in GitHub Desktop.
All Collection properties should be instantiated for types with empty constructors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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