Recently I noticed ReSharper’s built-in test runner doesn’t require you to decorate your fixtures as TestFixture — it’s smart enough to locate Test methods regardless. My team noticed this too, and as a result we’ve started to omit TestFixture entirely.

Turns out this is a big mistake. NUnit itself requires them — in our case, we discovered our build server (which calls NUnit directly) was ignoring a large number of tests (including some that were failing), and was reporting much lower code coverage results than expected.

So, somehow we need to enforce that the TestFixture attribute is applied everywhere it should be, so us lazy ReSharper developers don’t miss anything. Not to worry… we can write a test for that!

[TestFixture]
public class MissingTestFixtureAttributeTests
{
    [Test]
    public void All_test_fixtures_must_have_test_fixture_attribute()
    {
        IEnumerable<Type> badFixtures =
            from t in Assembly.GetExecutingAssembly().GetTypes()
            where HasTests(t)
            where IsMissingTestFixtureAttribute(t)
            select t;

        ErrorIfAny(badFixtures);
    }

    static bool HasTests(Type type)
    {
        var testMethods =
            from m in type.GetMethods()
            from a in m.GetCustomAttributes(typeof (TestAttribute), true)
            select m;

        return testMethods.Any();
    }

    static bool IsMissingTestFixtureAttribute(Type type)
    {
        var attributes =
            from a in type.GetCustomAttributes(typeof (TestFixtureAttribute), true)
            select a;

        return !attributes.Any();
    }

    private static void ErrorIfAny(IEnumerable<Type> fixtures)
    {
        if (!fixtures.Any())
            return;

        var sb = new StringBuilder("The following types are missing [TestFixture] attributes:");
        sb.AppendLine();
        foreach(Type type in fixtures)
        {
            sb.AppendLine();
            sb.Append(type);
        }

        throw new Exception(sb.ToString());
    }
}
May 13th, 2010 | 2 Comments

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

August 31st, 2009 | No Comments Yet

One small problem I encountered when getting into Dependency Injection (DI) and Inversion of Control (IoC) was that even though all my services were now beautifully SOLID and test-driven, quite often it was all wasted because I forgot to register them in my IoC container, causing massive errors that wouldn’t be detected until runtime (oops).

Luckily, it is very easy to write a test to check everything has been registered properly. All you need is a bit of reflection to find all the interfaces in an assembly, then try to resolve them all:

[Test]
public void Should_be_able_to_resolve_all_interfaces_in_domain()
{
    var domain = Assembly.GetAssembly(typeof(Book));
    var interfaces = domain.GetTypes().Where(t => t.IsInterface);
    foreach (Type @interface in interfaces)
    {
        Assert.IsNotNull(ServiceLocator.Current.GetInstance(@interface));
    }
}

We can make this even nicer with NUnit 2.5. Instead of a for loop with multiple asserts within one test case (hmm) that can only show one failure at a time (ugh), we can use NUnit parameterized tests to automagically generate a separate test case for each interface we need to resolve:

NUnit parameterized tests

That’s heaps easier to read (otherwise Unity’s exceptions are very terse), and we can see multiple failures in one run. To make NUnit generate this without typing them all out by hand, all you need is the new ValueSource attribute, which lets you choose a method, field or property or method that returns an IEnumerable set of objects:

public IEnumerable<Type> GetDomainInterfaces()
{
    var domain = Assembly.GetAssembly(typeof(Book));
    return domain.GetTypes().Where(t => t.IsInterface);
}

[Test]
public void Should_be_able_to_resolve_domain_service(
    [ValueSource("GetDomainInterfaces")]Type @interface)
{
    Assert.IsNotNull(ServiceLocator.Current.GetInstance(@interface));
}

Note I include this with my integration tests, because it can take a few secs to run (e.g. I keep my NHibernate ISession in the container, and building the session factory takes a long time).

June 8th, 2009 | 2 Comments