Who Practices Test-Driven Development (TDD)?
27 Mar 2006Harry 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:
$auth = new myAuth;
$auth->username = 'chris';
$auth->password = 'mypass';
if ($auth->checkLogin()) {
/* SUCCESS */
} else {
/* FAILURE */
}
(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:
include 'test-more.php';
plan(2);
$auth = new myAuth;
{
/* Test Valid Credentials */
$auth->username = 'chris';
$auth->password = 'mypass';
ok($auth->checkLogin(), 'test valid credentials');
}
{
/* Test Invalid Credentials */
$auth->username = 'chris';
$auth->password = 'notmypass';
ok(!$auth->checkLogin(), 'test invalid credentials');
}
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.