Test object with file system functions

I am writing some objects that make extensive use of the file system. I am not sure if this is the right way to test them.

I know theoretically, I have to abstract the functionality of the file system in some objects and then mock them, but in my case it would be completely pointless: the main use of the classes that I want to test is to manage files. Therefore, I would have the same problem when testing new objects that are just shifted one level.

The only way I can do the tests is to actually work with the file system. The problem is that the tests will run both in the browser and on the command line, so I need to work in a directory with write access for everyone. Moreover, this is not a very portable solution.

Any ideas?

+3
source share
4 answers

You can make fun of the file system with vfsStream as suggested in the PHPUnit Handbook :

vfsStream - , [...] PEAR , :

$ pear channel-discover pear.bovigo.org
$ pear install bovigo/vfsStream-beta

Github, Wiki

+5

php-, , , .

, , (, , ). , , PHP. unit test , , .

+1

, :

  • , , . , (% TEMP%, /), , .
  • IO . . ( ). , , file.Read , , ioThingie.loadSettings().
  • IO ( Gordon ).

, #, - (System.IO.File), , , vfs , FS, .

+1

mock PHP-, runkit. , , . phpunit-mockfunction - PHPUnit, PHP.

, :

class Tests extends PHPUnit_Framework_TestCase {
    // ... setUp, tearDown, other tests...

    function test_1(){
        $file_size_to_return = 10;

        $fake_filesize = new PHPUnit_Extensions_MockFunction('filesize', $this->obj->tested_method);
        $fake_filesize->expects($this->once())->will($this->returnValue($file_size_to_return));

        $this->obj->tested_method(); // actually run method we want test that contains filesize() function...
    }
}
+1

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


All Articles