crcr(If you haven’t downloaded SimpleTest framework yet, click here.)
You will probably become a Test-infected developer if you try a unit testing framework! But what is unit testing?
"The basic concept of unit testing is write more code which will test the main code we've written, by "throwing" sample data at it and examining what it gets back."-Harry Fuecks.
Some developers might not like the idea of writing more code but it will save you a good time pin pointing the exact piece of code causing the problem when your script becomes large.
Time to get practical about UnitTesting! We will write a test case for a simple file manipulation class. This file class will have the basic operations needed to manipulate files. It will be able to create, read, write, append and delete files and our test case should test each operation individually.
First, here is the definition of the class:
[file.class.php]
<?php class File { var $filename;
/** * Constructor * will take care of creating the file if it does not exists. * @param string $file */ function File($file) { if (empty($file)) die('Filename should not be empty');
$this->filename = $file;
//if the file does not exists and we can not create it, terminate the script if (!$this->exists() && !$this->create()) die('Unable to find/create the file'); }
/** * checks if the file exists or not! * @return bool */ function exists() { return file_exists($this->filename); }
/** * This method will attempt to create a file if it does not exists. * @return bool */ function create() { //if the file exists, save the trouble opening it. if ($this->exists()) return true;
return $this->putContents(null); }
/** * reads the file's contents and returns it.. * @return string */ function getContents() { return @file_get_contents($this->filename); }
/** * writes to the file.. * @param string $content * @return bool */ function putContents($content) { $fp = @fopen($this->filename, 'wb'); $write = @fwrite($fp, $content); @fclose($fp);
return !($write === false); }
/** * append data to the file.. * @param string $content * @return bool */ function append($content) { $fp = @fopen($this->filename, 'ab'); $append = @fwrite($fp, $content); @fclose($fp);
return !($append === false); }
/** * deletes the file.. * @return bool */ function delete() { return @unlink($this->filename); } } ?> |
I will assume that you are able to understand how the code works since we are talking about unit testing which is far more advanced than file manipulation.
If you can't understand how this class works, I suggest you learn first about OOP then learn about unit testing.
Anyway, it's not the best file class out there because I created it just for this tutorial so don't get mad about it ;)