I am trying to write unit tests for a file import export module.
One of my method checks that a filename passed exists.
How would this be mocked and a test written to check if the file exists or not?
Unit tests are supposed to prove that a unit of code functions correctly in complete isolation. If your test depends on the file system to function correctly in order to pass, your test is suboptimal and could be lying to you on any given test run.
Like any experiment, when you have more than one variable in play, you can't be sure of your results. For PHP code that interacts with the file system, it's best to mock the file system using a custom stream wrapper (usually vfsStream, but you can easily write your own stream wrapper if you really want to).
$noTest < $testWithFileSystemDependency < $testThatMocksFileSystem
Usually, this is accomplished by passing file paths into the methods that use them directly:
<?php
function myFunction($someFilePath) {
// do stuff
}
In this way, you can mock the file system and pass in a testable dummy path that will behave how you have mocked it to behave.
Personally I just create _files
directory in the tests directory and create files there. Or in /tmp
.
There is a way to mock the fs: http://www.phpunit.de/manual/current/en/test-doubles.html#test-doubles.mocking-the-filesystem but from my experience - I prefer real FS operations (in this case).