考虑以下场景(这不是生产代码):
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
is a stream wrapper
for a virtual filesystem
这在单元测试中非常有用,可以模拟真实的文件系统。您可以从安装它composer https://packagist.org/packages/mikey179/vfsStream.
更多信息请访问:
https://github.com/mikey179/vfsStream https://github.com/mikey179/vfsStream
https://phpunit.de/manual/current/en/test-doubles.html https://phpunit.de/manual/current/en/test-doubles.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)