Who Practices Test-Driven Development (TDD)?

27 Mar 2006

Harry Fuecks maintains a good blog over at Sitepoint and recently wrote a piece on Evaluating PHP Applications.

Noel Darlow, a regular contributor to the Sitepoint forums (and someone whose opinion I respect), comments:

I think testing is a good indicator of the developer's ability. I'll be looking for tests being used to drive the design and not just the odd unit test stuck on after the fact.

I'm a big advocate of testing, and although I won't claim to be an expert on the topic, I have to question whether it's necessary that tests drive the design. It seems plausible that someone could choose to write tests after the implementation, and I don't think ignorance is necessarily the reason.

On the other hand, I find myself taking this approach more and more. For example, when I'm designing a function or class, I start with an example that describes how I want to use it:

  2. $auth = new myAuth;
  4. $auth->username = 'chris';
  5. $auth->password = 'mypass';
  7. if ($auth->checkLogin()) {
  8.     /* SUCCESS */
  9. } else {
  10.     /* FAILURE */
  11. }

(Sorry if my ad hoc example doesn't live up to your standards.)

I'll usually type this out at least once, so it's not just imagined. In order to implement myAuth, I can choose to keep this example in mind as I write the code, or I can take this simple example and turn it into a real test or two:

  2. include 'test-more.php';
  4. plan(2);
  6. $auth = new myAuth;
  8. {
  9.     /* Test Valid Credentials */
  10.     $auth->username = 'chris';
  11.     $auth->password = 'mypass';
  13.     ok($auth->checkLogin(), 'test valid credentials');
  14. }
  16. {
  17.     /* Test Invalid Credentials */
  18.     $auth->username = 'chris';
  19.     $auth->password = 'notmypass';
  21.     ok(!$auth->checkLogin(), 'test invalid credentials');
  22. }

It's so easy to write tests, I might even write some for a blank username, blank password, etc. I can do all this without writing a single line of code, and when I begin writing the code, I already have a simple test suite to run - I don't have to write some quick ad hoc tests just to see whether things are working as planned. When all the tests pass, I know I've accomplished my initial design goals.

How many of you test? How many of you write your tests first?

Note: If you happen to be attending PHP Quebec later this week, I'm giving a talk that will discuss some simple approaches to testing.