Alan Dean

CTO, Developer, Agile Practitioner

Photograph of Alan Dean

Tuesday, June 15, 2010

Cavity Unit Testing

I have started a new open source project on google code which I've named Cavity for no particular reason other than it's somewhat memorable: http://code.google.com/p/cavity/ and I plan on pushing up some of the code I use to accelerate and assist development, starting with an internal DSL for unit testing type and property definitions.

I’ve been doing TDD for about 9 years now and have, I admit, derived a somewhat idiosyncratic style which involves asserting all of the external characteristics of a type. I don’t agree with those who argue in favour of not testing properties (I disagree because properties have behaviour and thus ought to be verifiable). I also believe that interface implementations and attribute decorations should be verifiable (which also speaks to my belief in what I call intentional development). However there is a downside to this, which is that asserting type and property definitions is slower than not doing so (obviously) and so I use my unit test DSL to accelerate the process and thus mitigate the impedance. This has been living inside the SimpleWebServices project for a while now but I thought it was time to promote it to a more formal offering and so it is the first library available from Cavity.

To give you a flavour, here are a couple of examples of testing a class and a property:

[Fact]
public void type_definition()
{
    Assert.True(new TypeExpectations<Class1>()
        .DerivesFrom<object>()
        .IsConcreteClass()
        .IsUnsealed()
        .HasDefaultConstructor()
        .Implements<IFoo>()
        .IsDecoratedWith<CustomAttribute>()
        .Result);
}

[Fact]
public void value_definition()
{
    Assert.True(new PropertyExpectations<Class1>("Value")
        .TypeIs<string>()
        .DefaultValueIs("default")
        .Set("example")
        .ArgumentNullException()
        .ArgumentOutOfRangeException(string.Empty)
        .FormatException("invalid")
        .IsNotDecorated()
        .Result);
}

The binaries and source are zipped for download and to see more examples, please visit the wiki:

2 comments:

Neil Mosafi said...

Nice idea, still not sure if I'd bother though will bear it in mind!

One suggestion is using something other than Assert.True() as you'll just get "Expected True, was False". Would be better to get your testing helpers to output detailed information about which expectations didn't pass, otherwise it'll be hard to see why the test fails.

Alan Dean said...

Neil,

A TestException is thrown on an expectation failure with the reason given in the message.