
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:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
public function testAvatarUpload()
{
Storage::fake('avatars');
$response = $this->json('POST', '/avatar', [
'avatar' => UploadedFile::fake()->image('avatar.jpg')
]);
// Assert the file was stored...
Storage::disk('avatars')->assertExists('avatar.jpg');
// Assert a file does not exist...
Storage::disk('avatars')->assertMissing('missing.jpg');
}
}
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.
Filed in: Laravel Tutorials / Testing
Enjoy this? Get Laravel News delivered straight to your inbox every Sunday.
No Spam, ever. We'll never share your email address and you can opt out at any time.
Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.
Laravel Jobs

- Senior Laravel Engineer
-
Remote okay (must already live in USA)
Hawthorne Effect - Senior Software Engineer (Remote - Contract)
-
Remote
Koodi Systems - PHP Developer
-
Pittsburgh / Remote
Sequoia Waste Solutions - Software Developer
-
Eindhoven
Simac IDS - Application Developer Level II (CakePHP / MySql / Vue.js)
-
Lancaster, PA
Harbor Compliance - FULL STACK LARAVEL DEVELOPER
-
LONDON - WEST END
AMPERSAND HEATLH - Mid/Senior Laravel Developer - U.S. Developers Only
-
Kenner, Louisiana
Profit Miner Technologies
Empathy: the Cornerstone of Your Company Culture
Hard skills change constantly. Every year, developers must level up their skills to keep pace with the ever-changing…
Amazon releases a summary of the recent S3 outage
Amazon released a summary of the S3 Service Disruption on US-EAST-1 yesterday. The outage affected many sites, apps,…