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

标签 php mocking phpunit 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.");
        }
    }
}

对了,有什么问题吗?代码覆盖率报告此行未被覆盖:

throw new Exception("Cannot open file handle.");

这是正确的,但由于我是在逻辑上创建上面的文件夹,所以 fopen() 似乎不可能失败(除非在极端情况下,例如磁盘容量为 100%)。

我可以忽略代码覆盖率中的代码,但那是一种作弊。有什么方法可以模拟文件系统,使其可以识别 myFile.txt 并模拟无法创建文件的文件系统?

最佳答案

vfsStream虚拟文件系统流包装器,在单元测试中模拟真实文件系统很有用。您可以从 composer 安装它.

更多信息:

https://github.com/mikey179/vfsStream

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

关于PHPUnit:如何模拟这个文件系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12083134/

相关文章:

php - 使用限制时出错?

php - 注意:未定义的属性:stdClass::$user_id 位于 C:\wamp\www\social\includes\class-query.php 第 134 行

python - 用模拟替换对象

php 关于assertEquals的解释

php - 如何在 selenium PHP 单元中切换到 iframe

php - 我可以使用 usort 函数仅显示第二高(或第三……依此类推)值吗?

php - Yii2 - 在运行时附加组件

python - 如何在 Python 中模拟可调用实例的属性?

java - 检查 EasyMock 匹配器中的属性值

php - 模拟 security.context 在调用时被视为非对象