PHPUnit: How do I mock this file system?

南笙酒味 提交于 2020-01-01 08:33:04

问题


Consider the following scenario (this is not production code):

 class MyClass {
    public function myMethod() {
        // create a directory
        $path = sys_get_temp_dir() . '/' . md5(rand());
        if(!mkdir($path)) {
            throw new Exception("mkdir() failed.");
        }

        // create a file in that folder
        $myFile = fopen("$path/myFile.txt", "w");
        if(!$myFile) {
            throw new Exception("Cannot open file handle.");
        }
    }
}

Right, so what's the problem? Code coverage reports that this line is not covered:

throw new Exception("Cannot open file handle.");

Which is correct, but since I'm creating the folder above logically it would seem impossible for the fopen() to fail (except maybe in extreme circumstances, like disk at 100 %).

I could ignore the code from code coverage but thats kind of cheating. Is there any way I can mock the file system so that it can recognise myFile.txt and mock the file system unable to create the file?


回答1:


vfsStream is a stream wrapper for a virtual filesystem that is useful in unit tests to mock the real filesystem. You can install it from composer.

More Info at:

https://github.com/mikey179/vfsStream

https://phpunit.de/manual/current/en/test-doubles.html




回答2:


Yes!

You should inject the full path somehow, and don't call sys_get_temp_dir() right in that method.

Any non-existant path should trigger a problem. You don't need VFS for that.

BUT you will get a E_NOTICE (or warning perhaps?) before the exception is triggered. So you should probably first check is_writable, and throw the exception if it returns false.




回答3:


You could also break the function into 2 methods, one to create the path, and the other to use it. Then, individual tests could be done to ensure the path is created. A second set of tests could check and capture the exception when you try to use a bad path.



来源:https://stackoverflow.com/questions/12083134/phpunit-how-do-i-mock-this-file-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!