Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test object with filesystem functions

I'm writing some objects which make extensive use of the filesystem. I'm not sure what is the right way to test them.

I know in theory I should abstract filesystem functionality in some objects and then mock them, but it would be quite pointless in my case: the main use of the classes I want to test is to manage files. So I would have the same problem when testing the new objects, just shifted one level.

The only way I can think to make the tests is to actually work with the filesystem. The problem is that tests will be ran both in the browser and on the command line, and so I need to work in a directory with write access by everyone. Moreover, this does not seem to be a very portable solution.

Any ideas?

like image 638
Andrea Avatar asked May 26 '26 01:05

Andrea


2 Answers

You can mock the filesystem with vfsStream as suggested in the PHPUnit Manual:

vfsStream is a stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system […] If the PEAR installer is available on your system, you only need to execute the following commands:

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

There is examples at Github and also a Wiki

like image 199
Gordon Avatar answered May 28 '26 15:05

Gordon


Introduce very low level php functions that do nothing other than call file system functions, and use these within your code.

Then, in your test harness, override this functions with stubs (that possibly record that they've been called). That way you can verify that your code will, in the live system, call the correct low level PHP functions. For a unit test thats all you can do, really.

like image 44
PaulJWilliams Avatar answered May 28 '26 13:05

PaulJWilliams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!