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 に答える