Chapter 2. Automating Tests
Even good programmers make mistakes. The difference between a good programmer and a bad programmer is that the good programmer uses tests to detect his mistakes as soon as possible. The sooner you test for a mistake, the greater your chance of finding it, and the less it will cost to find and fix. This explains why it is so problematic to leave testing until just before releasing software. Most errors do not get caught at all, and the cost of fixing the ones you do catch is so high that you have to perform triage with the errors because you just cannot afford to fix them all.
Testing with PHPUnit is not a totally different activity from what you should already be doing. It is just a different way of doing it. The difference is between testing—that is, checking that your program behaves as expected—and performing a battery of tests—runnable code-fragments that automatically test the correctness of parts (units) of the software. These runnable code-fragments are called unit tests.
In this section, we will go from simple print
-based testing code to a fully automated test. Imagine that we have been asked to test PHP's built-in Array
. One bit of functionality to test is the function sizeof( )
. For a newly created array, we expect the sizeof( )
function to return 0
. After we add an element, sizeof( )
should return 1
. Example 1 shows what we want to test.
Example 1. Testing Array and sizeof( )
<?php $fixture = Array( ); // $fixture is expected to be empty. $fixture[] ...
Get PHPUnit Pocket Guide now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.