你可以通过几种方式做到这一点。
您可以创建一个包含一些内容的测试文件并在测试中使用该文件。这可能是最简单的,但这意味着为了让您的测试正常工作,您需要将此文件放在套件中。
为了避免跟踪测试文件,您可以模拟文件系统。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);
}