PHPUnit:我如何模拟这个文件系统? [英] PHPUnit: How do I mock this file system?

查看:24
本文介绍了PHPUnit:我如何模拟这个文件系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下场景(这不是生产代码):

Consider the following scenario (this is not production code):

 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.");
        }
    }
}

好吧,那有什么问题呢?代码覆盖率报告此行未被覆盖:

Right, so what's the problem? Code coverage reports that this line is not covered:

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

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

Which is correct, but since I'm creating the folder above logically it would seem impossible for the fopen() to fail (except maybe in extreme circumstances, like disk at 100 %).

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

I could ignore the code from code coverage but thats kind of cheating. Is there any way I can mock the file system so that it can recognise myFile.txt and mock the file system unable to create the file?

推荐答案

vfsStreamvirtual filesystemstream wrapper 非常有用在单元测试中模拟真实的文件系统.您可以从 composer 安装它.

vfsStream is a stream wrapper for a virtual filesystem that is useful in unit tests to mock the real filesystem. You can install it from composer.

更多信息在:

https://github.com/mikey179/vfsStream

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

这篇关于PHPUnit:我如何模拟这个文件系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆