Using NUnit to check domain event handlers are registered

We’ve been using Udi Dahan’s excellent Domain Events pattern in a project at work. It’s best to keep them as coarse-grained as possible, but we have already identified a dozen or so events that need to be raised by the domain and processed by our services layer.

Naturally, however, I am forgetting to register some of the event handlers in our IoC container. So, as before with our domain services, I decided to write some integration tests to check everything is set up properly. This is very simple to achieve using NUnit’s trusty parameterized tests, ServiceLocator and a sprinkling of generics:

IEnumerable<Type> GetDomainEvents()
{
    var domain = Assembly.GetAssembly(typeof(Employee));

    return domain.GetTypes()
        .Where(typeof(IDomainEvent).IsAssignableFrom)
        .Where(t => !t.Equals(typeof(IDomainEvent)));
}

[Test]
public void Should_be_able_to_resolve_handlers_for_domain_event(
    [ValueSource("GetDomainEvents")]Type @event)
{
    var handler = typeof (IHandles<>).MakeGenericType(@event);

    ServiceLocator.Current.GetAllInstances(handler).Should().Not.Be.Empty();
}

This reveals a nice todo list of all the handlers we haven’t implemented yet. And the ones I forgot to register!

NUnit Should_be_able_to_resolve_handlers_for_domain_event