Writing The Test Case
Now we want to create a test case for this class to see if it works as we expect or not!
To create a test case we have to create a new class which inherits from UnitTestCase class which is found in the file unit_tester.php which comes in SimpleTest framework package.
So we create our new PHP file, let's name it fileTest.php and include unit_tester.php and our file file.class.php:
[fileTest.php]
<?php include_once 'simpletest/unit_tester.php';
include_once 'file.class.php'; |
Of course you have to change the paths to the correct paths in your environment.
We now start the definition of the test case class and let's name it fileTest as well:
class fileTest extends UnitTestCase { var $file; var $filename;
function fileTest($filename) { $this->filename = $filename; $this->file = new file($this->filename); $this->UnitTestCase('File Manipulation Test'); }
function setUp() { $fp = @fopen($this->filename, 'x'); if (!($fp === false)) { fwrite($fp, ''); fclose($fp); } }
function tearDown() { @unlink($this->filename); } |
As you can see, we have defined 3 methods (including the constructor) and 2 data members, $file and $filename.
The constructor (fileTest) takes one argument which is the file name and assign it to the data member $filename and create the file object and assign it to $file.
The line: $this->UnitTestCase('File Manipulation Test'); is optional and it just makes a header line in the test reporter (we will talk about this later).
Also we have defined the methods setUp() and tearDown().
setUp() will be called automatically before each and every test and tearDown() will be called after each and every test. However, these two methods are optional.
We have defined the setUp() method to create a new clean file before each test and tearDown() will delete that file after each test.