Answer the question
In order to leave comments, you need to log in
How to mock a static method in tests in yii2?
The method under test calls a static method of another class (FileHelper::createDirectory($path);).
How to mock this method in yii2?
protected function _generateFolders()
{
$folders = str_split($this->hash, self::FOLDER_TITLE_LENGTH);
$folders = array_slice($folders, 0, $this->foldersDepth);
$folders = implode('/', $folders) .
($this->accessDir ? '/' . $this->accessDir : '');
$path = self::getPathToFiles() . '/' . $folders;
FileHelper::createDirectory($path);
return $folders;
}
Answer the question
In order to leave comments, you need to log in
I looked at the Yii code, it turns out they really use static methods for helpers ...
I don’t write in Yii, but I can advise you to stop using their static classes directly, and work through your own wrapper.
That is, make the MySuperHelpers class, in which to encapsulate all the work with statics, and already use your class everywhere. Those:
<?php
class MyHelpers {
public function makeDirectory($path)
{
return FileHelper::createDirectory($path);
}
}
By the way, another option. If you have a method in your class that uses statics or, say, should access the file system, which you don’t want to do in tests, you can explicitly move this functionality into a separate private method and lock it up. Get something like
class Actor
{
public function generateFolders()
{
$folders = str_split($this->hash, self::FOLDER_TITLE_LENGTH);
$folders = array_slice($folders, 0, $this->foldersDepth);
$folders = implode('/', $folders) .
($this->accessDir ? '/' . $this->accessDir : '');
$path = self::getPathToFiles() . '/' . $folders;
$this->createDirectory($path);
return $folders;
}
protected function createDirectory($path)
{
return FileHelper::createDirectory($path);
}
}
$actor = $this->getMock('Actor', ['createDirectory']);
$actor->expects($this->any())->method('createDirectory')->willReturn(true);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question