PHPUnit Cookbook 1.0

While there's pretty complete PHPUnit API documentation out there, and there's a PHPUnit manual, there's still not a lot of practical examples of using PHPUnit on the Internet, especially with its Mock interface. As a result, most people tend to stick to the tip of the iceberg in terms of the functionality that PHPUnit offers.

This book is an attempt to reverse that, by gathering together useful examples in an O'Reilly Cookbook-like format.

This book will include primarily code samples or even more generally, complete programs. Each should run directly as given. They have been tested using PHP version 5.3 and PHPUnit version 3.4.


Assertions

The basics of a unit test is to run through a unit of code (a function, cohesive set of functions, or object), and then assert that certain conditions are met. The most common condition is that a given return value is what was expected.

A PHPUnit TestCase has wide range of assertions built-in, and provides the building blocks to construct arbitrary assertions.


Mocks

A unit test properly checks a unit (a function or cohesive set of functions) of code, and only that unit. A unit, though, is generally only useful working in concert with other functions and objects in order to to make a shippable product. PHPUnit comes with functionality, in the form of its Mock interface, that enables you to generate useful stand-ins for other functions and objects on which the tested code relies.

Not only can the generated mocks effectively stub out non-unit functionality, they can be set up with expectations, which are assertions that the mocked out class is used as expected.