请考虑以下方案(这不是生产代码):
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
并模拟文件系统无法创建文件?