Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MichaelGrossklos's avatar

Testing file uploads with PHPUnit

Hi,

in my app a user can upload some images. Now I need to test this part. How kan i Fake a file upload with PHPUnit?

Tanks!

0 likes
3 replies
rikh's avatar

If you are using the Storage facade, then you can make use of the mocking features built into it to verify that the correct calls are made with the correct parameters.

http://laravel.com/docs/5.1/testing#mocking-facades

You can also mock Jobs and Events if needed...

http://laravel.com/docs/5.1/testing#mocking

If you want to really test that the file has really been uploaded to S3 or similar, then I'd make sure that things like the target bucket are configured in the environment, so you can send stuff to a test bucket in testing. You'd then have to just try and download your test file after the upload completes and ensure that it has the correct content. This will be slow though, so possibly put it in a separate set of tests that you don't have to run 500 times a day.

neomerx's avatar

Hi,

Excerpt from project

In PhpUnit post file might look like

        $response = $this->callPost(self::API_URL, $input, self::getMockFile());


    /**
     * @param string $fileName
     *
     * @return array
     */
    public static function getMockFile($fileName = 'i.jpeg')
    {
        $file = new UploadedFile(__FILE__, $fileName, null, null, null, true);
        return [ApiInterface::PARAM_ORIGINAL_FILE_DATA => $file];
    }

where callPost is just a wrapper over Laravel build in call function

    protected function callPost($url, $content, array $files = [])
    {
        return $this->call('POST', $url, [], [], $files, $this->getServerArray(), $content);
    }

You also have to mock file method call. A couple of examples of code that should be called before sending files


    /**
     * Set up file system mocks.
     */
    public static function setUpMocksForCreate()
    {
        Storage::shouldReceive('disk')->once()->withAnyArgs()->andReturnSelf();
        Storage::shouldReceive('writeStream')->once()->withAnyArgs()->andReturn(true);
    }

    /**
     * Set up file system mocks.
     */
    public static function setUpMocksForDelete()
    {
        Storage::shouldReceive('disk')->once()->withAnyArgs()->andReturnSelf();
        Storage::shouldReceive('delete')->once()->withAnyArgs()->andReturn(true);
    }

4 likes
MichaelGrossklos's avatar

I forgot to mention that my app is only an API and I want to upload the file to S3 and have to make sure that the file is really up.

Please or to participate in this conversation.