samayo samayo - 2 years ago 129
PHP Question

Writing test cases in unit-testing for file/image uploads

I am trying to write a test for

class. The problem is that, even though I know the basics of Unit Testing. I have a problem writing one for file uploads.

As far as my experience goes, I have only wrote very simple ones like check HTTP status corresponds some number, or check a link/div exists in a some page or assert the outcome of some function or class is similar and such and such..

But with image upload it is completely different scenario. Specially in this case, the class provides uploading, cropping, resizing and watermarking. So, seems writing an automated test case that checks each image is manipulated accordingly seems impossible for file uploads.

I'm hoping anyone can she some light on this problem.

Answer Source

Since this question has not been answered (rightly) for 2 years, I've decided to answer it myself since I have figured out the solution myself since then.

The answer turns out simple than I had thought, which simply is known as 'mocking'. In this case, when testing a file/image upload script, there is no physically upload images. All can be done with refactoring and isolating the function responsible for uploading, as in ..

Example of upload class

class Upload{
    function save(){
        return move_uploaded_file($tmp_name, $destination);

Example of using test for the upload class

class UploadTest{
    function save(){
        return true; 

There is nothing much into this, as method save() does not need to be tested considering it does not rely anymore on the class to upload the files/images

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download