user610217
user610217

Reputation:

Reflections on a unit test looking for generics in an interface

I want to write some unit tests to make sure my domain namespace and my IUnitOfWork interface are properly synced.

For example, if I have a domain entity of Foo, I should have a corresponding property of type IQueryable in my IUnitOfWork interface. So if I have:

namespace My.Domain 
{
    public class Foo : IEntity<Guid>
    {
        //properties
    }
}

namespace My.Interfaces
{
    public interface IUnitOfWork
    {
        public IQueryable<Foo> Foos { get; }
    }
}

I started my unit test like so:

private static readonly Assembly _assembly = typeof(Assembly.Class).Assembly;

[TestMethod]
public void AllEntitiesInNamespaceHaveCorrespondingIUnitOfWorkProperties()
{
    var classesInDomainNamespace = _assembly.GetTypes()
        .Where(x => string.Equals(x.Namespace, "My.Domain", StringComparison.Ordinal))
        .Distinct();

    var entitiesInUnitOfWork = typeof(IUnitOfWork).GetProperties()
        .Where(x => x.PropertyType.IsAssignableFrom(typeof(IQueryable<IEntity<Guid>>)))
        .Distinct();
}

...and this is where I started to run into problems. Ideally, I want to assert the number of records in classesInDomainNamespace and entitiesInUnitOfWork were the same, but things get weird when dealing with generics.

How would I write this unit test?

Upvotes: 0

Views: 41

Answers (1)

Sebastian Schumann
Sebastian Schumann

Reputation: 3446

Would this help?:

var entitiesInUnitOfWork = typeof(IUnitOfWork).GetProperties()
    .Where(x => 
        x.PropertyType.IsGenericType && 
        x.PropertyType.GetGenericTypeDefinition() == typeof(IQueryable<>) &&  
        typeof(IEntity<Guid>).IsAssignableFrom(x.PropertyType.GetGenericArguments()[0])
    .Distinct();

This is not testet. Not even compiled - but I hope it gives the correct hint.

Upvotes: 1

Related Questions