Last week, we introduced you to setting up a unit testing framework. This week, you will learn about running multiple tests simultaneously, creating more informative error messages, and more. This article, the second of three parts, is excerpted from chapter 6 of the book Advanced PHP Programming, written by George Schlossnagle (Sams; ISBN: 0672325616).
One of the benefits of using an even moderately mature piece of open-source software is that it usually has a good bit of sugar—or ease-of-use features—in it. As more developers use it, convenience functions are added to suit developers' individual styles, and this often produces a rich array of syntaxes and features.
Feature Creep - The addition of features over time in both open-source and commercial software is often a curse as much as it is a blessing. As the feature set of an application grows, two unfortunate things often happen:
Some features become less well maintained than others. How do you then know which features are the best to use?
Unnecessary features bloat the code and hinder maintainability and performance.
Both of these problems and some strategies for combating them are discussed in Chapter 8, "Designing a Good API."
Creating More Informative Error Messages
Sometimes you would like a more informative message than this:
PHPUnit 1.0.0-dev by Sebastian Bergmann.
.F.
Time: 0.00583696365356
There was 1 failure:
1) TestCase emailaddresstestcase->testlocalpart()
failed:
expected true, actual false
FAILURES!!!
Tests run: 2, Failures: 1, Errors: 0.
Especially when a test is repeated multiple times for different data, a more informative error message is essential to understanding where the break occurred and what it means. To make creating more informative error messages easy, all the assert functions that TestCase inherit from PHPUnit::Assert support free-form error messages. Instead of using this code:
function testLocalPart() {
$email = new EmailAddress("georg@omniti.com");
// check that the local part of the address is
equal to 'george'
$this->assertTrue($email->localPart == 'george');
}
which generates the aforementioned particularly cryptic message, you can use a custom message:
function testLocalPart() {
$email = new EmailAddress("georg@omniti.com");
// check that the local part of the address is
equal to 'george'
$this->assertTrue($email->localPart == 'george',
"localParts: $email->localPart of $email->address
!= 'george'");
}
This produces the following much clearer error message:
PHPUnit 1.0.0-dev by Sebastian Bergmann.
.F.
Time: 0.00466096401215
There was 1 failure:
1) TestCase emailaddresstestcase->testlocalpart()
failed:
local name: george of george@omniti.com != georg
FAILURES!!!
Tests run: 2, Failures: 1, Errors: 0.
Hopefully, by making the error message clearer, we can fix the typo in the test.