Test Driven Development (TDD) in a Nutshell

Here’s a brief overview of TDD:

  1. Write a test that fails (it fails because code that it tests is not written yet)
  2. Write just enough code so that the test passes
  3. Re-factor the code
  4. Repeat from step 2 until code is baked, then repeat from step 1.

Brief guidelines for good unit tests:

  • Write simple tests (if a test requires complex configuration and setup, it will eventually fall into disrepair).
  • Test one scenario at a time.
  • Tests are your specifications. Well written tests provide working specification of the code they test.
  • Name your tests accurately and consistently.
  • Use data that makes tests easy to read and understand.
  • Write tests that run quickly.
  • Make each test independent. You should be able to run them in any order.

The initial result of TDD is that you end up with a suite of tests to rely upon when you refactor your code. It gives you the courage to refactor freely and courageously, knowing that you have a ‘safety net’ that will tell you if you have broken existing functionality (providing you have sufficient test code coverage). But TDD also forces you to think like a consumer of your own code, with the positive side effect of producing cleaner, simpler designs.

The TDD sequence is often represented as follows (Note: Not the usual sequence for traffic lights!):

  • Red: Write a test (that fails)
  • Green: Write code to make test pass
  • Amber: Refactor until Green again, then repeat back at Red

Here are a few resources:

Books:
Test Driven Development: Kent Beck. Addison-Wesley.
Refactoring: Martin Fowler. Addison-Wesley.

Web:
http://www.agiledata.org/essays/tdd.html
Test-Driven Development in .NET by Peter Provost. An easy to understand introduction to TDD and unit testing.