文件操作类 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');
}
/**
* 描述:该函数将会在每次测试开始前自动调用,
* 在编写测试类的时候,是个可选函数,可写不可不写
*/
function setUp()
{
$fp = @fopen($this->filename, 'x');
if (!($fp == false)) {
fwrite($fp, '');
fclose($fp);
}
}
/**
* 描述:该函数将会在每次测试结束后自动调用,
* 在编写测试类的时候,是个可选函数,可写不可不写
*/
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());
?>