PHP Software Engineering
Writing a Unit Test
Problem
You’re working on a project that extends a set of core functionality, and you want an easy way to make sure everything still works as the project grows.
Solution
Write a unit test that tests the core functionality of a function or class and alerts you if something breaks.
A sample test using PHP-QA’s .phpt testing system is:
--TEST--
str_replace() function
--FILE--
<?php
$str = 'Hello, all!';
var_dump(str_replace('all', 'world', $str));
?>
--EXPECT--
string(13) "Hello, world!"
A sample test using the powerful and popular PHPUnit package is:
class StrReplaceTest extends PHPUnit_Framework_TestCase
{
public function testStrReplaceWorks()
{
$str = 'Hello, all!';
$this->assertEquals('Hello, world!', str_replace('all', 'world', $str));
}
}
Discussion
There are a number of ways to write unit tests in PHP. A series of simple .phpt tests may be adequate for your needs, or you may benefit from a more structured testing solution such as PHPUnit. We’ll discuss each approach, but the first question is: why write a unit test in the first place?
Writing an application from scratch in any language is a lot like peeling an onion, only in reverse. You start with the center of the onion, and build layers on top of layers until you get to the finished product: an onion.
The more layers you build on top of your core, the more important it is for that core to continue functioning as you expect it to. The easiset way to ensure that the core of an application continues functioning as expected, especially after modifications, is through unit tests.
In the earlier example, we’re testing that the str_replace() function successfully replaces one string with another. The test doesn’t care how the str_replace() function is written; all that matters is that it works as expected on a recurring basis.
The easiest way to run the .phpt test is to save it in a file ending in .phpt (str_replace.phpt, for example), and then use PEAR’s built-in .phpt execution tool, like this:
% pear run-tests str_replace.phpt
You’ll see output like this:
Running 1 tests
PASS str_replace() function[str_replace.phpt]
TOTAL TIME: 00:00
1 PASSED TESTS
0 SKIPPED TESTS
You can test a number of features of your core functionality by creating multiple .phpt files, and executing:
% pear run-tests *.phpt
For full details on the structure of .phpt files, visit http://qa.php.net/write-test.php.
You can also write unit tests using the PHPUnit unit testing framework.
If the PHPUnit test from the Solution is in a file named StrReplaceTest.php, once PHPUnit is installed, you can run the test like this:
% phpunit StrReplaceTest
That command will look for the file named StrReplaceTest.php and run the test defined within it.
PHPUnit is a very powerful unit testing framework that can do much more than run a simple test like in the example.
No comments:
Post a Comment