考虑以下场景(这不是生产代码):
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 安装它.
更多信息:
关于PHPUnit:如何模拟这个文件系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12083134/