Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit: How can I mock this file creation?

I want to mock the creation of a file using the vfsstream

class MyClass{

  public function createFile($dirPath)
  {
    $name = time() . "-RT";
    $file = $dirPath . '/' . $name . '.tmp';

    fopen($file, "w+");
    if (file_exists($file)) {
        return $name . '.tmp';
    } else {
        return '';
    }
  }
}

but when I try to test the file creation :

$filename = $myClass->createFile(vfsStream::url('/var/www/app/web/exported/folder'));

I get an error :

failed to open stream: "org\bovigo\vfs\vfsStreamWrapper::stream_open" call failed fopen(vfs://var/www/app/web/exported/folder)

I have see this question talking about mocking the fileSystem but it has no information about the file creation. Does the vfsstream support the file creation with the fopen function? How can I test the file creation?

like image 756
Dev DOS Avatar asked Jun 27 '17 07:06

Dev DOS


1 Answers

try creating with a setup the vsf stream, as example:

$root = vfsStream::setup('root');
$filename = $myClass->createFile($root->url());

hope this help

As working example:

/**
 * @test
 * @group unit
 */
public function itShouldBeTested()
{
    $myClass = new MyClass();

    $root = vfsStream::setup('root');
    $filename = $myClass->createFile($root->url());
    $this->assertNotNull($filename);
    var_dump($filename);
}

this will produce

(dev) bash-4.4$ phpunit -c app --filter=itShouldBeTested PHPUnit 4.8.26 by Sebastian Bergmann and contributors.

.string(17) "1498555092-RT.tmp"

Time: 13.11 seconds, Memory: 200.00MB

OK (1 test, 1 assertion)

like image 95
Matteo Avatar answered Oct 07 '22 13:10

Matteo