我对 PHPUnit 和 TDD 比较陌生,我想知道如何测试以下代码:
class File
{
/**
* Write data to a given file
*
* @param string $file
* @param string $content
* @return mixed
*/
public function put($path, $content)
{
return file_put_contents($path, $content);
}
}
如何在不实际创建文件的情况下测试文件是否已创建(显然是使用 PHPUnit)。
谢谢。
最佳答案
您可以通过使用类似 vfsStream 的虚拟文件系统来为您的单元测试模拟文件系统。带文档 here
编辑
一个例子是这样的:
class FileTest extends \PHPUnit_Framework_TestCase
{
/**
* @var vfsStreamDirectory
*/
private $root;
/**
* set up test environmemt
*/
public function setUp()
{
$this->root = vfsStream::setup('exampleDir');
}
/**
* test that the file is created
*/
public function testFileIsCreated()
{
$example = new File();
$filename = 'hello.txt';
$content = 'Hello world';
$this->assertFalse($this->root->hasChild($filename));
$example->put(vfsStream::url('exampleDir/' . $filename), $content);
$this->assertTrue($this->root->hasChild($filename));
}
}
关于PHPunit 文件测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24499175/