Test driven development (TDD) has been around, as a concept at least, for nearly 15 years. However, it’s still gaining acceptance with some developers and industries.

Here’s the basics:

  1. write a failing end-to-end test
  2. write a failing unit test.
  3. write just enough code to make the unit test pass.
  4. repeat 2 and 3 until the end-to-end tests have passed

This implies TDD’s golden rule: Never write new features unless you have a failing test.

The first step allows you to think about your design activity upfront; this is great because you will often uncover edge cases which would otherwise have been missed. The second step makes you think about what you are going to do on a low level, and leaves a guard in place to stop you breaking things in the future. Finally, the third step lets you know when you’ve done enough to make your application work.

TDD is often seen as the holy grail of good development practices. However, in the real world, developers will still implement new features before writing the corresponding failing tests. Of course it’s always possible to go back and write the unit tests retrospectively. However, this can sometimes be tricky and doesn’t bring the full benefits of TDD.

Unit Tests

One of the benefits of unit tests is that they can give you instant feedback about the quality of your code. For example, if you find it hard to write tests for a particular class, then it probably has one of the following problems:

  • it does too many things
  • it hides the wrong information (e.g. using private/protected when you shouldn’t )
  • it has unfocused responsibilities
  • it is tightly coupled to other parts of the system

But, don’t be put off! This information allows you to identify where you should refactor your code until you can cover all of it with unit tests. In my next post I’m going to walk through an example of TDD using MVC4 .NET and Entity Framework.

< Back