Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 8 ■ TESTING, DEPLOYMENT, AND CONTINUOUS INTEGRATION^113

> phpunit DemoTest
PHPUnit 3.1.9 by Sebastian Bergmann.
F
Time: 0 seconds
There was 1 failure:
1) testSum(DemoTest)
Failed asserting that <integer:0> matches expected value <integer:4>.
/home/user/myfirstrepo/tests/DemoTest.php:12

FAILURES!
Tests: 1, Failures: 1.

The test failed because the sum() method no longer passes your equality assertion that
2 + 2 = 4.
You can choose from literally dozens of assertions. In the example, you used assertEquals
and assertNotEquals, both of which take two items to compare. There are also assertions like
assertSame for objects, assertTrue or assertFalse for Booleans, and setExpectedException for
exceptions. For a reference list and exact syntax details, see the PHPUnit manual at http://
http://www.phpunit.de.
When writing unit tests, you will need to set up your objects, as when you assigned $demo = new
Demo() in the previous test. This can become tedious if you are always doing the same setup for
each test. Fortunately, PHPUnit provides two methods, called setUp() and tearDown(), which
allow you to define a common configuration for every test. Listing 8-3 shows the same test,
split into setUp() and tearDown() methods.

Listing 8-3. A Test Split into setUp and tearDown Methods (./tests/DemoTest.php)

<?php
require_once('PHPUnit/Framework.php');
require_once(dirname(__FILE__). '/../code/Demo.php');

class DemoTest extends PHPUnit_Framework_TestCase {
public function setUp() {
$this->demo = new Demo();
}

public function testSum() {
$this->assertEquals(4,$this->demo->sum(2,2));
}

public function testSubstract() {
$this->assertEquals(0,$this->demo->subtract(2,2));
}

public function tearDown() {
unset($this->demo);
}
}

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

Free download pdf