Unit tests – keep it simple (KISS)!

I have a tendency to overcomplicate things sometimes. Unit tests, are one such piece of code, that you want to keep as simple and clean as possible, so that other developers can easily find out how your class-or-method-under-test is supposed to work. There’s a principle for that that says it very strongly – “Keep it simple, stupid.”

Don’t make it flexible when it does not have to be (just … hard code it). For example, when I was working on IInterceptorSelector support for Castle DynamicProxy, I had to test proxies without target, where return value is set by an interceptor.

My first attempt at it was to create ReturnDefaultOfTInterceptor class that for any given return type, would instantiate it with parameterless constructor. This solution would provide what I needed, but it was unnecessarily complicated and made the test less readable. I didn’t need a helper class (that’s what the interceptor was in this test) that would handle just any return type of just any method. For the test I was calling one method, with one return type, and that’s all I needed from my helper interceptor.

Once I realize that I changed the test to something like this:

[Test]
public void SelectorWorksForInterfacesOfInterfaceProxyWithoutTarget()
{
    var options = new ProxyGenerationOptions
    {
        Selector = new TypeInterceptorSelector<ReturnFiveInterceptor>()
    };
    var proxy = generator.CreateInterfaceProxyWithoutTarget(
    typeof(ISimpleInterface),
        new[] { typeof(ISimpleInterfaceWithProperty) }, 
        options,
        new ReturnFiveInterceptor()) 
    as ISimpleInterfaceWithProperty;
    Assert.IsNotNull(proxy);
    var i = proxy.Age;
    Assert.AreEqual(5, i);
} 

The ReturnFiveInterceptor class name clearly sais what the class does. Also the assertion in the last line is more obvious now.

So, keep your tests simple and readable, don’t generalize where you don’t really need to, but know your limits, because when you cross the line you’re on the fragile tests territory.

Technorati Tags: , ,