Suppose I have the following class:
class FooBar
{
public function getArrayFromFile($file)
{
if (!is_readable($file)) {
return [];
}
return include $file;
}
}
Assuming $file contains the following:
return [
...
];
How does one test it? Specifically how do you create a double for "include".
You can do it a couple of ways.
You can create a test file that contains some contents and use that file in your test. This is probably the easiest but it means that in order for your tests to work you need to have this file located in the suite.
To keep from having to keep track of test files you can mock the file system. The PHPUnit documentation recommends using vfsStream. This way you can create a fake file and using that in your method. This will also make it easier to set permissions so that you can test the
is_readablecondition.http://phpunit.de/manual/current/en/phpunit-book.html#test-doubles.mocking-the-filesystem
So in PHPUnit your test would look like this: