Currently, PHPUnit does not support an integrated component to perform test independently on Filesystem. The project suggests the usage of a support library, called "vfsStream" and written by Frank Kleine: it can be downloaded as an open-source library on "github" from address: https://github.com/mikey179/vfsStream.

“vfsStream” is a wrapper capable to prepare a "virtual file system", creating in RAM memory the representation of a virtual file system. Using such library, you can work in isolated manner while performing tests, without the risk to leave files in the test structure, that could add false 'failing tests", due to an unforeseen interruption during previous tests.

To integrate the library, you have simply to add the relevant dependency via "composer":

{
  "autoload": {
    "psr-0": {
      "": "src"
    }
  },
  "require": {
    "phpunit/phpunit": "4.*",
    "mikey179/vfsStream": "1.3.*"
  }
}

By way of example, you can consider a simple object implementing a method to remove a file at a specified path.

class Remover
{
    public function delete($path)
    {
        unlink($path);
    }
}

Your test needs simply to prepare the library and then: "testRemove" will simply call the method and check in the virtual file system the removal of the created file.

<?php

use orgbovigovfsvfsStream;

class RemoverTest extends PHPUnit_Framework_TestCase
{
    private $root;

    public function setUp()
    {
        $this->root = vfsStream::setup("myrootdir");
    }

    public function testRemove()
    {
        $remover = new Remover();

        $this->assertFalse($this->root->hasChild('myfile.txt'));
        file_put_contents(vfsStream::url('myrootdir/myfile.txt'), "my content");
        $this->assertTrue($this->root->hasChild('myfile.txt'));

        $remover->delete(vfsStream::url('myrootdir/myfile.txt'));
        $this->assertFalse($this->root->hasChild('myfile.txt'));
    }
}

"vfsStream" does not support all operations that can be performed on a real disk, due to the fact that it is not able to act on a physical file system. Among the missing operations, that can not be implemented, there are the following: “realpath()”, “symlink()” “touch()”, “chown()”, “chgrp()” and “chmod()”.

Comments

comments powered by Disqus

cloudparty

Follow Us