文件操作類 file.class.php
<?php
class File
{
var $filename;
function File($file)
{
if (emptyempty($file)) {
die('Filename should not be empty');
}
$this->filename = $file;
if (!$this->exists() && !$this->create()) die('Unable to find / create the file');
}
function exists()
{
return file_exists($this->filename);
}
function create()
{
if ($this->exists()) return true;
return $this->putContents(null);
}
function getContents()
{
return @file_get_contents($this->filename);
}
function putContents($content)
{
$fp = @fopen($this->filename, 'wb');
$write = @fwrite($fp, $content);
@fclose($fp);
return !($write === false);
}
function append($content)
{
$fp = @fopen($this->filename, 'ab');
$append = @fwrite($fp, $content);
@fclose($fp);
return !($append === false);
}
function delete()
{
return @unlink($this->filename);
}
}
?>
單元測試類 fileTest.php
<?php
//include_once '../simpletest/unit_tester.php';
//include_once '../simpletest/reporter.php';
include_once('../simpletest/autorun.php');
include_once 'file.class.php';
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');
}
/**
* 描述:該函數(shù)將會在每次測試開始前自動調(diào)用,
* 在編寫測試類的時候,是個可選函數(shù),可寫不可不寫
*/
function setUp()
{
$fp = @fopen($this->filename, 'x');
if (!($fp == false)) {
fwrite($fp, '');
fclose($fp);
}
}
/**
* 描述:該函數(shù)將會在每次測試結(jié)束后自動調(diào)用,
* 在編寫測試類的時候,是個可選函數(shù),可寫不可不寫
*/
function tearDown()
{
@unlink($this->filename);
}
function testFileExists()
{
$this->assertTrue($this->file->exists());
clearstatcache();
$this->assertTrue(file_exists($this->file->filename));
}
function testCreate()
{
$this->tearDown();
$this->assertFalse(file_exists($this->file->filename));
clearstatcache();
$this->assertTrue($this->file->create());
$this->assertTrue(file_exists($this->file->filename));
}
function testReadWrite()
{
$contents = 'content';
$this->assertTrue($this->file->putContents($contents));
$this->assertEqual($this->file->getContents(), $contents);
}
function testAppend()
{
$this->file->putContents('SimpleTest');
$this->assertTrue($this->file->append('NeverMind'));
$this->assertWantedPattern('~nevermind$~i', $this->file->getContents());
}
function testDelete()
{
$this->assertTrue($this->file->delete());
$this->assertFalse(file_exists($this->filename));
}
}
$test = new fileTest('test.txt');
$test->run(new HtmlReporter());
?>