PHPunit 文件测试

Mel*_*ans 5 php testing tdd phpunit unit-testing

我对 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如何在不实际创建文件的情况下测试文件是否已创建(显然是使用 PHPUnit)。

谢谢。

Mar*_*ker 4

您可以使用vfsStream等虚拟文件系统来模拟单元测试的文件系统,并在此处提供文档

编辑

一个例子是这样的:

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));
    }
}
Run Code Online (Sandbox Code Playgroud)