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:我如何模拟这个文件系统?


基础教程推荐
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01