5

I'm relatively new to PHPUnit and TDD, and I was wondering how I might test the following code:

class File
{
    /**
     * Write data to a given file
     * 
     * @param string $file
     * @param string $content
     * @return mixed
     */
    public function put($path, $content)
    {
        return file_put_contents($path, $content);
    }
}

How can I test if the file was created WITHOUT actually creating the file (with PHPUnit obviously).

Thanks.

1 Answer 1

4

You can mock the file system for your unit tests by using a virtual file system like vfsStream with documentation here

EDIT

An example would be something like:

class FileTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var  vfsStreamDirectory
     */
    private $root;

    /**
     * set up test environmemt
     */
    public function setUp()
    {
        $this->root = vfsStream::setup('exampleDir');
    }

    /**
     * test that the file is created
     */
    public function testFileIsCreated()
    {
        $example = new File();
        $filename = 'hello.txt';
        $content = 'Hello world';
        $this->assertFalse($this->root->hasChild($filename));
        $example->put(vfsStream::url('exampleDir/' . $filename), $content);
        $this->assertTrue($this->root->hasChild($filename));
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I will definitely take a look. Is it also possible to do mock the file system with Mockery, or by myself. I'm curious how the file system is being mocked.
vfsStream basically creates a wrapper around the file:// stream, allowing it to simulate all filesystem functions. As far as I'm aware, it can be used with any test framework (phpunit, simpletest, phpspec, etc), including helpers like mockery
Could you maybe give me an example of how I would use vfsStream within the code that I supplied with my question? If its not too much asked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.