Sunday, January 22, 2012

More Readable tests using SpecificationFor<T>

Introduction

In my current role at an agile company we work in pairs and following XP principles, one of which is TDD. I’ve been following TDD for a few years now and one thing I think that helps me when I come back to old tests and helps other developers who are new to a project is when a test has a "context".

Example of a test with context

class When correcting a customers address with no postcode Then ???

Then what? Well that’s the great thing about working in a pair you get to discuss what should happen in the above "context". Perhaps it should log an error, perhaps it should throw an exception, perhaps it should just do nothing? Who knows but at least the context is in the test.

Another example of a test with context

class When correcting a customers address with a valid address Then ???

Again the name of the class should help kick start the discussion between the pair.

If you compare that to a class without a context:

Example of test without context

class CustomerFixtures Then ???

It’s not quite the same and doesn’t really lend it’s self to discussion about behaviour, what do you think?

I don't want to pretend I invented any of these concepts. They've been around for a while now, it's called BDD or Behaviour driven design. For me though it's more about making your tests readable and more importantly understandable from just looking at the class and method names. Do a search for "Context Specification" on your favourite search engine and you'll find lots more examples.

Code

Enough talking get with the code. Here are 2 small helper classes that have been adapted from a “Specification Context” example I found on the interwebs. This works with NUnit. I hope you’ll find it useful: