Testing File Uploads With Laravel

Laravel now includes a new system for testing file uploads through two new fake methods, one on the UploadFile class and another on the Storage facade.

As the documentation shows here is a full test showing it in use:


namespace TestsFeature;

use TestsTestCase;
use IlluminateHttpUploadedFile;
use IlluminateSupportFacadesStorage;
use IlluminateFoundationTestingWithoutMiddleware;
use IlluminateFoundationTestingDatabaseMigrations;
use IlluminateFoundationTestingDatabaseTransactions;

class ExampleTest extends TestCase
    public function testAvatarUpload()

        $response = $this->json('POST', '/avatar', [
            'avatar' => UploadedFile::fake()->image('avatar.jpg')

        // Assert the file was stored...

        // Assert a file does not exist...

You can also customize the files width, height, and size for testing validation:

UploadedFile::fake()->image('avatar.jpg', $width, $height)->size(100);

Or create other types of files like PDF’s:

UploadedFile::fake()->create('document.pdf', $sizeInKilobytes);

This feature is in the latest Laravel release and you can find out more details in the official documentation.

Source: Laravel News