Why should I practice Test Driven Development and how should I start?

There are a lot of benefits:

  • You get immediate feedback on if your code is working, so you can find bugs faster
  • By seeing the test go from red to green, you know that you have both a working regression test, and working code
  • You gain confidence to refactor existing code, which means you can clean up code without worrying what it might break
  • At the end you have a suite of regression tests that can be run during automated builds to give you greater confidence that your codebase is solid

The best way to start is to just start. There is a great book by Kent Beck all about Test Driven Development. Just start with new code, don't worry about old code... whenever you feel you need to refactor some code, write a test for the existing functionality, then refactor it and make sure the tests stay green. Also, read this great article.


The benefits part has recently been covered, as for where to start....on a small enterprisey system where there aren't too many unknowns so the risks are low. If you don't already know a testing framework (like NUnit), start by learning that. Otherwise start by writing your first test :)


Benefits

  1. You figure out how to compartmentalize your code
  2. You figure out exactly what you want your code to do
  3. You know how it supposed to act and, down the road, if refactoring breaks anything
  4. Gets you in the habit of making sure your code always knows what it is supposed to do

Getting Started

Just do it. Write a test case for what you want to do, and then write code that should pass the test. If you pass your test, great, you can move on to writing cases where your code will always fail (2+2 should not equal 5, for example).

Once all of your tests pass, write your actual business logic to do whatever you want to do.

If you are starting from scratch make sure you find a good testing suite that is easy to use. I like PHP so PHPUnit or SimpleTest work well. Almost all of the popular languages have some xUnit testing suite available to help build and automate testing.