Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^112) CHAPTER 8 ■ TESTING, DEPLOYMENT, AND CONTINUOUS INTEGRATION
Listing 8-2. A Unit Test (./tests/DemoTest.php)
<?php
require_once('PHPUnit/Framework.php');
require_once(dirname(FILE). '/../code/Demo.php');
class DemoTest extends PHPUnit_Framework_TestCase {
public function testSum() {
$demo = new Demo();
$this->assertEquals(4,$demo->sum(2,2));
$this->assertNotEquals(3,$demo->sum(1,1));
}
}
Now, in the tests directory, run your test using the phpunit test runner:



phpunit DemoTest
PHPUnit 3.1.9 by Sebastian Bergmann.
Time: 0 seconds
OK (1 test)
As you can see, the test runner reports that your test ran correctly.



Understanding PHPUnit


Now that you know where to put unit tests and how to call them from the command line, you
might be wondering what a PHPUnit_Framework_TestCase is and how the testSum() method works.
PHPUnit tests typically follow a naming convention where the test class is named the same as
the class being tested followed by the word Test, and the file it’s located in has the same name as the
test class with a .php extension. The test class name should be descriptive of the component or
functionality being tested. For example, a class that tests user authentication (the Authentication
class) should be called AuthenticationTest and stored in AuthenticationTest.php.
Tests—or more specifically, test cases—are simply classes that inherit from PHPUnit_
Framework_TestCase. This test class provides access to all the different types of assertions and is
responsible for running all the test methods against the target class.
In our example, when the test runner is passed the DemoTest class, it calls each of the testing
methods one at a time, collecting information along the way. Inside each method, you define a
set of assumptions about what the code being tested will do. These assumptions need to be
translated into an assertion. If you expect that the sum() of 2 and 2 will always be 4, then you
would write an assertion that the function result is equal to 4.
Without changing DemoTest, modify the Demo class so that its sum() method no longer returns a
valid result; changing the + operator to - will do the trick. Once the Demo class is changed, you
should get a result like the following when you run your unit test again:

McArthur_819-9C08.fm Page 112 Friday, February 22, 2008 9:06 AM

Free download pdf