Pro PHP- Patterns, Frameworks, Testing and More

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

Creating Your First Unit Test


To get started creating your unit tests, you need to set up a directory structure. There is no
particular convention as to where to place your tests. Some developers keep their test files in
the same directory as the code being tested. Others create a separate tests directory and mirror
the code directory structure, which helps keep testing code separate. In this example, you will
use the latter approach.
First, clean up your Subversion file:

> svn rm index.html newfile.txt

D index.html
D newfile.txt
> svn commit

Deleting index.html
Deleting newfile.txt

Committed revision 5.

■Note Using svn rm will remove the file from the repository as well as the checkout upon svn commit.
A standard rm will not remove the file from the repository, and the file will be restored the next time you use
svn update.

Now create two directories, one for code and one for your tests:

> svn mkdir code tests
A code
A tests

In the code directory, create a Demo class that does something easily tested—addition and
subtraction—as shown in Listing 8-1.

Listing 8-1. A Demo Class (./code/Demo.php)

<?php
class Demo {
public function sum($a,$b) {
return $a+$b;
}
public function subtract($a,$b) {
return $a-$b;
}
}

Next, create a unit test, as shown in Listing 8-2.

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

Free download pdf