Now
we are ready to go.
Starting Unit Testing
A unit test is actually a collection of different tests against your code. It is not a big
job to write unit tests using PHPUnit. All you have to do is simply follow a set of
conventions. Let's take a look at the following example, where you create a string
manipulator class, which returns the number of words available in a string.
//class.wordcount.php
class wordcount
{
public function countWords($sentence)
{
return count(split(" ",$sentence));
}
}
?>
Reflection and Unit Testing
[ 114 ]
Now we will write a unit test for this class. We have to extend the
PHPUnit_Framework_TestCase to write any unit test. And we have to use
PHPUnit_Framework_TestSuite to create the test suite, which actually holds a
collection of tests. Then we will use PHPUnit_TextUI_TestRunner to run the tests
from the suite and print the result.
//class.testwordcount.php
require_once "PHPUnit/Framework/TestCase.php";
require_once "class.wordcount.php";
class TestWordCount extends PHPUnit_Framework_TestCase
{
public function testCountWords()
{
$Wc = new WordCount();
$TestSentence = "my name is afif";
$WordCount = $Wc->countWords($TestSentence);
$this->assertEquals(4,$WordCount);
}
}
?>
Running the test:
//testsuite.
Pages:
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129