Wednesday, July 27, 2016

Hassle-Free Filesystem Operations during Testing? Yes Please!

When working with the filesystem in our tests suites, a big concern is cleaning up the temporary files after each test runs. However, if for any reason the test's execution is interrupted before the cleanup phase, further tests might fail, as the environment has not been cleaned up.

In this post, we will use a library named vfsStream to create filesystem mocks. It's little more than a wrapper around a virtual filesystem, which also works very nicely with PHPUnit.

Note This post requires a basic understanding of unit testing and PHPUnit.

To have something to test, we'll write a simple class for creating files:

<?php
// FileCreator.php
class FileCreator {

    public static function create($path, $name, $content)
    {
        $file_name = rtrim($path, '/') . '/' . $name;

        if (file_put_contents($filename, $content)){
            return true;
        }
        return false;
    }
}

Inside the class, we have a create() method, which accepts the filename, content, and a path to which to save it.

To test the class, we first take the traditional approach, and create a test class without using a virtual filesystem. Then, we'll bring vfsStream into the game to see how it can simplify the testing process for us.

Traditional Approach

<?php

class FileCreatorTest {

    protected $path;

    public function setUp()
    {
        $this->path = sys_get_temp_dir();
    }

    public function tearDown()
    {
        if (file_exists($this->path . '/test.txt')) {
            unlink($this->path . '/test.txt');
        }
    }

    public function testCreate()
    {
        $this->assertTrue(FileCreator::create($this->path, 'test.txt', 'Lorem ipsum dolor sit amet'));
        $this->assertFileExists($this->path . '/test.txt');

    }

In the above, we define the temporary directory (in setUp()) which we'll use for our temporary files by using PHP's sys_get_temp_dir(). The function returns the system's directory path for temporary files.

Continue reading %Hassle-Free Filesystem Operations during Testing? Yes Please!%


by Reza Lavaryan via SitePoint

No comments:

Post a Comment