I'd really like to start implementing Unit Testing in my projects. I don't know how viable this is to do in PHP. If anyone has done this, how was it implemented? Did it increase productivity?

Accepted Answer

I've tried SimpleTest and PHPUnit, and stuck with PHPUnit because it works with PHP 5, and SimpleUnit seemed to throw a lot of notices and warnings (I like to develop with full error reporting turned on, there's no excuse for sloppy code). I also came across numerous bugs with SimpleTest (some of which caused me hours of wasted productivity and stress in trying to track them down).

In terms of how unit-testing helps development, I find TDD (Test Driven Development) to be the best paradigm, because it forces you to think exactly how your code will be used before you write any of it. In fact, since I've adopted unit-testing and tdd, I've rewritten much of my own code because in writing tests for them, I've realised that my method names and functions weren't exactly the most intuitive, and also did some things that they shouldn't have been doing (i.e. like doing two tasks, instead of being specific and just do one each).

Not only that, but writing tests for your code helps you understand your own code better (i.e. in that it helps you realise when your all-singing-and-dancing class is doing too many different things, and should be split up into different distinct components), and also helps others understand your code (because if you write your tests properly and elegantly, they can see how they're supposed to use your class - it's almost like writing code examples).

There's a good guide involving a bowling game here that gives you an insight to both PHPUnit and TDD, and that should help you get started. It starts from slide 14.

Written by JamShady
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki