Chapter 13. Testing: Ensuring Your Program Does the Right Thing

How do you know your program does what you think it does? Even with your careful attention to detail, are you sure that sales tax calculation function works properly? How do you know?

This chapter is about giving you the peace of mind that comes with answers to those questions. Unit testing is a way of making assertions about small bits of your code—“If I put these values into this function, I should get this other value out.” By creating tests that check the behavior of your code in appropriate situations, you can have confidence in how your program behaves.

PHPUnit is the de facto standard for writing tests for PHP code. Your tests are themselves little bits of PHP code. The following section describes how to install PHPUnit. “Writing a Test” shows some code and a first test for it. Use and run this code to make sure you’ve got PHPUnit installed properly and understand the basic pieces of a test.

Then, “Isolating What You Test” looks at how to narrow the focus of what you’re testing for maximum efficiency.

“Test-Driven Development” extends the tested code by adding some tests for code that doesn’t exist yet, and then adding the code to make the tests pass. This technique can be a handy way to ensure you’re writing code that is tested properly.

At the end of this chapter, “More Information About Testing” provides details on where to find more information about PHPUnit and testing in ...

Get Learning PHP 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.