1

我有一个简单的打开(文件)方法,如果它无法在给定路径中打开或创建文件,它应该抛出异常:

const ERR_MSG_OPEN_FILE = 'Failed to open or create file at %s';

public function open($filePath)
{
    ini_set('auto_detect_line_endings', TRUE);

    if (false !== ($this->handler = @fopen($filePath, 'c+'))) {
        return true;
    } else {
        throw new \Exception(
            sprintf(self::ERR_MSG_OPEN_FILE, $filePath)
        );
    }
}

使用 PHPUnit 和 VFSStream 围绕它进行单元测试:

$structure = [
        'sample.csv' => file_get_contents(__DIR__ . '/../sampleFiles/small.csv')
    ];

$this->root = vfsStream::setup('exampleDir', null, $structure);

$existingFilePath = vfsStream::url('exampleDir') . DIRECTORY_SEPARATOR . 'sample.csv';

$this->file = new File();
$this->file->open($existingFilePath);

上述设置创建了一个包含模拟文件(从现有 CSV 文件读取/克隆)的虚拟目录结构,这满足了 open 方法打开文件的要求。而且,如果我传递不同的路径(不存在文件),它将在同一个虚拟结构中创建。

现在为了覆盖异常,我想向现有结构添加一个现成的目录,假设一个文件夹属于另一个用户,我没有写权限,就像我尝试打开一个不存在的该文件夹中的文件,尝试创建一个应该失败,并且 open 方法应该抛出异常。

唯一的问题是,....我不知道该怎么做:D

任何建议、提示和指导将不胜感激:)

4

1 回答 1

0

您可以简单地将模拟目录的 url 指向不正确的路径。

$existingFilePath = vfsStream::url('badExampleDir') . DIRECTORY_SEPARATOR . 'incorrect.csv';

考虑到badExampleDir从未设置过,您的方法将无法在其中创建文件。

于 2015-08-16T18:45:00.140 回答