Why unit testing? There are quite a few reasons, but those I can think of right now are:
- It’s not hard, all it takes is some time to think things through
- Whenever I get a bugreport, I try to write it as a test to make sure this bug can never slip into my code unnoticed.
- It’s a nice way to make sure that the things you already wrote, keep working after you’ve changed some of your code.
Let’s take a look at the steps you need to do to get this working in Zend Studio (currently I’m using 6.1.2). First you need to add the PHPUNIT library location to the include of the project you want to write unit tests for. Right click your project, then click ‘properties’.
Then click on the ‘include path’ to the left. You will see an overview of the already added ‘include paths’ to this project.
Click the ‘add variable’ option and select ‘PHPUNIT_HOME’ and click ‘OK’.
So far, so good. Now we have to create a PHPUNIT Test Case. Rightclick on the folder where you want to this new file to go and click ‘new’ > ‘PHPUnit Test Case’.
I used the details below and did not select a specific element to test. If you do choose an element or class to test, all the default test methods will be added to the new file.
When you’re done adding the test file, you’ll get a pretty messy generated file. I’ve changed bits of it and added a few ‘demo’ functions as you can see below.
I wrote 4 tests, using the 3 methods ‘returnTrue’, ‘returnFalse’ and ‘greaterThan’. These methods are obviously pretty straightforward, but it gives you an idea of the way that you can test them.
You can run the test by rightclicking the editor area and choosing ‘run as’ > ‘PHPunit Test’.
You should, considering your configuration has been set properly, get the next results.
I broke the ‘greaterThan’ function on purpose, to make sure that those tests would fail and then you get the following results.
So far this little basic post about unit testing with PHPUnit from within Zend Studio. There are a lot more ways to test your code, but this brief introduction should get you started.