Virtual File System (VFS) simulates file system operations in unit tests, avoiding the hassle of cleaning temporary files. This article describes how to use the vfsStream
library to simplify the testing of file system operations in PHP unit tests.
First of all, we have a simple FileCreator
class for creating files:
<?php namespace App\Tests; class FileCreator extends PHPUnit_Framework_TestCase { public static function create($path, $name, $content) { $filename = rtrim($path, '/') . '/' . $name; return file_put_contents($filename, $content) !== false; } }
The traditional method requires setting a temporary directory in the setUp()
method and cleaning the temporary files in the tearDown()
method:
<?php namespace App\Tests; class FileCreatorTest extends PHPUnit_Framework_TestCase { protected $path; public function setUp() { $this->path = sys_get_temp_dir(); } public function tearDown() { $file = $this->path . '/test.txt'; if (file_exists($file)) { unlink($file); } } public function testCreate() { $this->assertTrue(FileCreator::create($this->path, 'test.txt', 'Lorem ipsum')); $this->assertFileExists($this->path . '/test.txt'); } }
This method is prone to errors when handling multiple files or test interrupts.
Use vfsStream
to avoid these problems. First, use Composer to install:
composer require mikey179/vfsStream
Then, modify the test class:
<?php use org\bovigo\vfs\vfsStream; class FileCreatorTest extends PHPUnit_Framework_TestCase { protected $vfs; public function setUp() { $this->vfs = vfsStream::setup('testDirectory'); } public function testCreate() { $path = vfsStream::url('testDirectory'); $this->assertTrue(FileCreator::create($path, 'test.txt', 'Lorem ipsum')); $this->assertFileExists($this->vfs->getChild('test.txt')->url()); } }
vfsStream::setup()
Created a virtual file system where all operations are performed in memory without manual cleaning. After the test is completed, the virtual file system will be automatically destroyed.
vfsStream
provides more powerful features such as permission control, file size control and complex directory structure simulation. This method avoids problems caused by temporary file cleaning failure in testing and improves the reliability of the test.
It should be noted that the original image link /uploads/20250214/173949279267ae8db8e54d6.webp
cannot be accessed, so the image cannot be displayed. If a valid image link is provided, I will include it in the output.
The above is the detailed content of Hassle-Free Filesystem Operations during Testing? Yes Please!. For more information, please follow other related articles on the PHP Chinese website!