轻松搞定文件操作测试!fidry/filesystem让你的SymfonyFilesystem更强大

在项目开发过程中,特别是涉及到文件操作时,编写可靠的单元测试至关重要。symfony Filesystem 组件提供了强大的文件系统操作能力,但对于测试来说,仍然存在一些痛点,比如临时目录的管理、文件的清理等等。

fidry/filesystem

库正是为了解决这些问题而诞生的。

通过composer在线学习地址:学习地址

fidry/filesystem

实际上是对 Symfony Filesystem 的一个轻量级封装,它主要提供了以下几个方面的增强:

  • FileSystem

    类扩展: 继承自 Symfony 的

    FileSystem

    类,并添加了一些额外的实用方法。

  • FS

    静态类: 当你不想使用依赖注入来管理文件系统层时,可以使用

    FS

    静态类,它提供了对文件系统操作的静态访问方式。

  • FileSystemTestCase

    PHPUnit 测试用例: 这是最核心的特性,它提供了一个方便的基类,让你能够轻松编写文件系统相关的单元测试。

使用 composer 安装

fidry/filesystem

非常简单:

<pre class="brush:php;toolbar:false">composer require fidry/filesystem

下面是一个使用

FileSystemTestCase

的示例:

<pre class="brush:php;toolbar:false"><?php declare(strict_types=1);  namespace App;  use FidryFileSystemFS; use FidryFileSystemTestFileSystemTestCase; use PHPUnitFrameworkAttributesCoversClass; use SymfonyComponentFinderFinder; use function getenv; use function is_string;  final class MyAppFileSystemTest extends FileSystemTestCase {     public static function getTmpDirNamespace(): string     {         // This is to make it thread safe with Infection. If you are not using         // infection or do not need thread safety, this can return a constant         // string, e.g. your project/library name.         $threadId = getenv('TEST_TOKEN');          if (!is_string($threadId)) {             $threadId = '';         }          return 'MyApp'.$threadId;     }      public function test_it_works(): void     {         // This file is dumped into a temporary directory. Here         // something like '/private/var/folders/p3/lkw0cgjj2fq0656q_9rd0mk80000gn/T/MyApp/MyAppFileSystemTest10000'         // on OSX.         FS::dumpFile('file1', '');          $files = Finder::create()             ->files()             ->in($this->tmp);          self::assertSame(['file1'], $this->normalizePaths($files));     } }

在这个例子中,

FileSystemTestCase

会自动为你创建一个临时目录,并在测试结束后清理所有文件。你可以使用

FS::dumpFile()

等方法在临时目录中创建文件,然后使用 Symfony Finder 组件来查找文件,最后进行断言。

fidry/filesystem

简化了文件系统相关的单元测试,让你能够专注于测试逻辑本身,而无需花费大量时间在环境准备和清理上。如果你正在使用 Symfony Filesystem 组件,并且需要编写文件系统相关的单元测试,那么

fidry/filesystem

绝对值得尝试。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享