PHPUnit: How can I mock this file?

I want to make fun of file creation with 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 check file creation:

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

I get an error message:

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

I see this question talking about the mockery of the file system, but it has no information about creating the file. Does vfsstream support file creation with the fopen function? How can I check file creation?

+4
source share
2 answers

try creating a vsf stream with tuning, for example:

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

,

:

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

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

(dev) bash -4.4 $phpunit -c app --filter = itShouldBeTested PHPUnit 4.8.26 .

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

: 13,11 , : 200,00

(1 , 1 )

+2

OOP :   

interface FileClientInterface {
    function open($path);
    function exist($path);
}

class FileClient implements FileClientInterface {
    function open($path)
    {
        fopen($path, "w+");
    }

    function exist($path)
    {
        return file_exists($path);
    }
}

class MyClass
{
    private $fileClient;

    /**
     * MyClass constructor.
     * @param $fileClient
     */
    public function __construct(FileClientInterface $fileClient)
    {
        $this->fileClient = $fileClient;
    }

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

        $this->fileClient->open($file);
        fopen($file, "w+");
        if ($this->fileClient->exist($file)) {
            return $name . '.tmp';
        } else {
            return '';
        }

    }
}

class MockFileClient implements FileClientInterface {
    public $calledOpen = 0;
    public $calledExists = 0;

    public function open($path)
    {
        $this->calledOpen ++;
    }

    public function exist($path)
    {
        $this->calledExists++;
    }

}


//not the test
$mockFileClient = new MockFileClient();
$myClass = new MyClass($mockFileClient);
$myClass->createFile('/test/path');

print_r($mockFileClient->calledOpen . PHP_EOL);
print_r($mockFileClient->calledExists . PHP_EOL);

, (FileClientInterface) , ( ). . , - .

0

Source: https://habr.com/ru/post/1680178/


All Articles