I’ve tried, off and on, to unit test file upload objects in various Laravel projects with no real success. I don’t want to mock it and I don’t want to acceptance test a form. It doesn’t exist yet. I want a real file to so I can make calls over it to make sure I get all the data out I need. That I can detect an image, manipulate it using various packages, see the results and tweak till I’m happy and know that it is working when it goes into the app. In short, I’m TDD’ing the API of an object. If that makes sense.
In any case, after much Googling, testing, documentation look up and reading code I figured it out. Hopefully it helps someone else too.
Here’s the code and a bit of explaination…
When a file is uploaded to Laravel, a Symfony component creates a UploadedFile object form the $_FILE global. This object changes hands several times and ends up being converted to Laravel’s UploadedFile object. Then it is on to being dropped into the Request object that you can pick up in controllers and such.
What this code does is manually create the Symfony object and then manually converts that over to Laravel’s UploadedFile object. Fun. The arguments you see in the Symfony object instantiation are…
- path to the file on disk. I stored it in a folder named “files” in the same directory as the test.
- file name.
- mime type.
- size of the file in bytes.
- how I feel inside. Actually it is number of errors. Same thing.
- boolean confirming that this is being used for testing.
I hope this makes someones day. I almost laid a golden egg when this emerged from my night of profanity.