So we are writing another test case. Let's add this new test case in our
class.testwordcount.php:
public function testCountWordsWithNewLine()
{
$Wc = new WordCount();
$TestSentence = "my name is \n\r Anonymous";
$WordCount = $Wc->countWords($TestSentence);
$this->assertEquals(4,$WordCount);
}
And let's run the suit again. What is the result now?
PHPUnit 3.0.5 by Sebastian Bergmann.
...
Time: 00:00
OK (3 tests)
That's pretty satisfying. All our tests are running ok. The function is now a good one.
This is how unit test can help us in real life.
Testing an Email Validator Object
Now, let's repeat the steps again. This time we will write unit tests for our brand new
Emailvalidator class which our developer said is a good one. Let's take a look at
our validator function first:
//class.emailvalidator.php
class EmailValidator
{
public function validateEmail($email)
{
$pattern = "/[A-z0-9]{1,64}@[A-z0-9]+\.[A-z0-9]{2,3}/";
preg_match($pattern, $email,$matches);
return (strlen($matches[0])==strlen($email)?true:false);
}
}
?>
Chapter 5
[ 117 ]
And here comes our test case:
class TestEmailValidator extends PHPUnit_Framework_TestCase
{
private $Ev;
protected function setup()
{
$this->Ev = new EmailValidator();
}
protected function tearDown()
{
unset($this->Ev);
}
public function testSimpleEmail()
{
$result = $this->Ev->validateEmail("has.
Pages:
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132