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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 < $testThatMocksFileSystemUsually, this is accomplished by passing file paths into the methods that use them directly:
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.