Search code examples
unit-testingsymfonyphpunitsymfony-2.8

how to mock file copy in a functional test


I have a controller which duty is copying a file passed along with the request (through a body POST) to a specific path under web/images. The path is specified by a property living into the specific Controller.

What I would like to do is testing it with a functional test, but I wouldn't like it to overwrite files in my project, so I would like to use vfs or change the path before my test case sends the request.

Is there a good-straight way to accomplish this?


Solution

  • I'll try to answer myself: I refactored my code in order to have a property that specifies the path I would like to copy/overwrite my file.

    Then, inside a PHPUnit class I replace the object property's value with a vfsStream path. By doing like that I get the behavior I need, without touching my real files/paths. Everything will live inside the virtual file system and my object will use it.

    Parameters are important for a clean and reusable code, but even more when you want to unit-test: I think Unit testing is helping me to force to parameterize everything in place of relapsing to hardcoding when you don't have so much time. In order to help me writing unit tests I created a class that accesses methods and properties, irrespective of their accessibility.

    PHPUnitUtils

    I'm quite sure there's already something more sophisticated, but this class fullfills my needs in this very moment. Hope it helps :-)