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?
推荐答案
vfsStream
是 virtual filesystem
的 stream 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
相关文章