Test Driven Development

What’s the best way to sleep at night and what’s the best way to be fairly sure that you’re code is as bullet proof as possible? Learn about test driven development and learn to love tests! There have been numerous articles that go in depth about this subject so I’ll {try} be brief about it…

No real purist will distill TDD into just a few guidelines but I will anyways:

  • Think about what functionality you want to build. Design and code a test that will test that functionality (before you code the actual functionality!).
  • Run the test and make sure it fails as expected.
  • Code your functionality.
  • Run your test again. Did it pass? Congrats, move on to the next task. Didn’t pass? You have some bug fixing to do.

The trick here is to put more emphasis on the design of the functionality than you’re used to. Think it through and design it so that it’s testable. If your test fails after coding the functionality and you feel compelled to fix the test rather than the functionality, then one of two things happened: 1) you did not give enough thought to the design of the functionality and make it easily testable or 2) you coded the test wrong. In either case, the design part of it all needed work.

Rinse, repeat, rinse, repeat.

The beauty in having a suite of tests is piece of mind. No, not just a warm fuzzy feeling. I’m talking about time-saving, bug-identifying, save-my-ass, look-ma-no-bugs piece of mind. Did you just add a new feature or refactor some code? Run your suite of tests. You’ll be able to much more quickly spot the bugs. Perhaps you’ll spot something that might have otherwise gone live.

I personally use SimpleTest to do my testing. PHPUnit is supposed to be pretty good as well.

Some links if you want to read more:
http://www.onpk.net/talks/fosdem2005/introduction_simpletest.html
http://www.developerspot.com/print/php/test-driven-development/


1 Comment »

  1. Raydius said

    I’ve been using TDD on one of my projects for just a few weeks and I do have to admit it makes for a lot of time saving. Gone is the meaningless repetition of recompiling broken code until it gets fixed.

RSS feed for comments on this post · TrackBack URI

Leave a Comment