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:
1<?php 2 3namespace Tests\Feature; 4 5use Tests\TestCase; 6use Illuminate\Http\UploadedFile; 7use Illuminate\Support\Facades\Storage; 8use Illuminate\Foundation\Testing\WithoutMiddleware; 9use Illuminate\Foundation\Testing\DatabaseMigrations;10use Illuminate\Foundation\Testing\DatabaseTransactions;1112class ExampleTest extends TestCase13{14 public function testAvatarUpload()15 {16 Storage::fake('avatars');1718 $response = $this->json('POST', '/avatar', [19 'avatar' => UploadedFile::fake()->image('avatar.jpg')20 ]);2122 // Assert the file was stored...23 Storage::disk('avatars')->assertExists('avatar.jpg');2425 // Assert a file does not exist...26 Storage::disk('avatars')->assertMissing('missing.jpg');27 }28}
You can also customize the files width, height, and size for testing validation:
1UploadedFile::fake()->image('avatar.jpg', $width, $height)->size(100);
Or create other types of files like PDF’s:
1UploadedFile::fake()->create('document.pdf', $sizeInKilobytes);
This feature is in the latest Laravel release and you can find out more details in the official documentation.
Filed in: