Unit Testing File Upload Postprocessing

Hello everyone!

I’ve been trying my hands on a somewhat stateless file upload: User uploads a file, the controller processes it and returns a form with pre-filled out fields based on the values from the file. The uploaded file is not saved in any manner.
Fortunately, I was successful :stuck_out_tongue:
Now, I want to write unit tests for this function, and I am stuck as to how I would approach that.
I’ve tried already to use setFiles() in the test case like so:

$request = $this->getRequest();
$request->setFiles(new Parameters(
                [
                    'fileUpload' => [
                        'name' => 'project.xml',
                        'type' => 'text/xml',
                        'tmp_name' => __DIR__.'/project.xml',
                        'error' => 0,
                        'size' => 128885
                    ]
                ]
            ));
        $this->dispatch('/thing/add', 'POST', ['importButton' => 'Import']);

But PHP considers this ‘an illegal file upload’ (which is understandable imho).
How would I ‘legally’ upload a file in this scenario? Or is another approach such as overwriting the $form->isValid() (in the controller) via stub more viable?

Thanks a lot!

You can define the PHP’s global variable $_FILES like below

        $_FILES['files'] = [
            'name' => [
                'project.xml'
            ],
            'type' => [
                'text/xml'
            ],
            'tmp_name' => [
                __DIR__ . '/project.xml'
            ],
            'error' => [
                0
            ],
            'size' => [
                128885
            ]
        ];

Hope this helps

I’ve really abandoned the notion since this post, but i’d like to highlight something the linked post talks about:

Basically, you can manipulate the $_FILES superglobal directly in the setUp() of your unit tests. Next, use mock objects for any external sort of service, otherwise you’re not truly unit testing, but integration testing.

Haven’t tried that, but from a distance, this does look like a valid solution.

Thanks, praem.