0

假设我有以下课程:

class FooBar
{
    public function getArrayFromFile($file)
    {
        if (!is_readable($file)) {
            return [];
        }

        return include $file;
    }
}

假设 $file 包含以下内容:

return [
...
];

如何测试它?具体来说,您如何为“包含”创建双精度。

4

1 回答 1

1

你可以通过几种方式做到这一点。

您可以创建一个包含一些内容的测试文件并在测试中使用该文件。这可能是最简单的,但这意味着为了让您的测试正常工作,您需要将此文件放在套件中。

为了避免跟踪测试文件,您可以模拟文件系统。PHPUnit 文档推荐使用vfsStream。这样你就可以创建一个假文件并在你的方法中使用它。这也将使设置权限变得更容易,以便您可以测试is_readable条件。

http://phpunit.de/manual/current/en/phpunit-book.html#test-doubles.mocking-the-filesystem

因此,在 PHPUnit 中,您的测试将如下所示:

public function testGetArrayFromFile() {
    $root = vfsStream::setup();
    $expectedContent = ['foo' => 'bar'];
    $file = vfsStream::newFile('test')->withContent($expectedContent);
    $root->addChild($file);

    $foo = new FooBar();
    $result = $foo->getArrayFromFile('vfs://test');

    $this->assertEquals($expectedContent, $result);
}

public function testUnreadableFile() {
    $root = vfsStream::setup();

    //2nd parameter sets permission on the file.
    $file = vfsStream::newFile('test', 0000); 
    $root->addChild($file);

    $foo = new FooBar();
    $result = $foo->getArrayFromFile('vfs://test');

    $this->assertEquals([], $result);
}
于 2014-07-30T14:26:49.557 回答