PHPUnit: How do I mock this file system?(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
这篇关于PHPUnit:我如何模拟这个文件系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHPUnit:我如何模拟这个文件系统?


- 从 PHP 中的输入表单获取日期 2022-01-01
- Laravel 仓库 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01