Mealybar.co.uk

Getting started with PHPUnit

conceived

I've been adding and modifying tests in an existing PHPUnit test suite for the last few years, mostly at work. My experience has gone through the usual stages of, anger - do we really need to waste time doing this, resistence - ok it caught that bug but still, acceptance - without tests I dont trust this bit of code, to embracing it. Time had come to setup my own test suite for one of my personal projects.

Sadly my Googling found lots of nothing with only a couple of limited bits of something, so here's my piecing together of those little bits of something.

I develop on a Mac and use MAMP, the first stage was to download and install PHPUnit. For that, this guide worked like a charm.

In the parent-most directory I created a tests folder - the intention is to mirroring my application directory structure. I also created a bootstrap.php file. This file will run just before the test suite setting anything up, at the moment it just deals with initiating my class autoloader.

Alongside that I created the PHPUnit configuration file phpunit.xml. Getting this file right was the trickiest bit of the setup, the documentation is only a notch above woeful. But here's what I ended with:

<phpunit
	bootstrap="bootstrap.php"
	colors="true"
	convertErrorsToExceptions="true"
	convertNoticesToExceptions="true"
	convertWarningsToExceptions="true"
	stopOnFailure="true">
	<testsuites>
		<testsuite name="Unit Tests">
			<directory suffix="test.php">./</directory>
		</testsuite>
	</testsuites>
	<php>
		<ini name="error_reporting" value="-1"/>
	</php>
</phpunit>

Going through it line by line.

bootstrap="bootstrap.php" - a file that runs before the test suite, can deal with setting up autoloader or creating a test database and connection, etc.

colors="true" - just uses colours in the terminal window

convertErrorsToExceptions="true", convertNoticesToExceptions="true", convertWarningsToExceptions="true", stopOnFailure="true" - setting these all to true makes sure any issue with my code will cause the tests to fail

<testsuites... - you can define all sorts of things here, I've kept it simple initially. All files named <anything>test.php will be picked up and tested.

<php... - you can set anything that you'd find in your php.ini here, I just make sure all error reporting is on.

So finally opening the terminal in the tests folder and running phpunit returns something like this.

example PHPUnit output in Mac OS X Terminal

Comments? Tweet me @mealybar, smoke signals, or homing pigeon, or something :)