PHPUnit — Mocking the real file system

How to use a stream wrapper for a virtual file system and have fun!

Ideneal
The Startup

--

Photo by James Pond on Unsplash

You could be in that situation where you have to test the creation of a file or something else operation into the file system but you don’t want to mess up it.

Suppose you have to test a command that generates a CSV report file, you should make a test class like this one:

In the example above, you need to check always in the tearDown method if the file exists and remove it if yes.

In this case, the vfsStream library cames in handy! vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. Let’s test now!

First of all, you need to install it:

composer require --dev mikey179/vfsstream

After that, the test case becomes the following:

--

--