PHPUnit:我如何模拟这个文件系统?

Ell*_*nce 11 php phpunit mocking vfs-stream

请考虑以下方案(这不是生产代码):

 class MyClass {
    public function myMethod() {
        // create a directory
        $path = sys_get_temp_dir() . '/' . md5(rand());
        if(!mkdir($path)) {
            throw new Exception("mkdir() failed.");
        }

        // create a file in that folder
        $myFile = fopen("$path/myFile.txt", "w");
        if(!$myFile) {
            throw new Exception("Cannot open file handle.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对,那有什么问题?代码覆盖率报告此行未涵盖:

throw new Exception("Cannot open file handle.");
Run Code Online (Sandbox Code Playgroud)

哪个是正确的,但是因为我在逻辑上创建了上面的文件夹,所以fopen()失败似乎是不可能的(除非在极端情况下,例如100%的磁盘).

我可以忽略代码覆盖中的代码但这有点作弊.有什么方法可以模拟文件系统,以便它可以识别myFile.txt和模拟无法创建文件的文件系统?

rai*_*ace 9

vfsStreamstream wrappervirtual filesystem这是在单元测试中有用的嘲弄真实的文件系统.你可以从composer安装它.

更多信息:

https://github.com/mikey179/vfsStream

https://phpunit.de/manual/current/en/test-doubles.html