Testing File Uploads In Laravel PHP Unit

Posted on

The Scenario

In PHP unit when we would like to test the upload functionality of our site it is best (in most cases) to not actually upload anything to anywhere and instead use Laravels helpful Facade mockery capabilities.

The Code

// The name of the drive to use, for example profile pictures will not be placed in the same place as post images

// make a fake file using Laravel's facade mockery interface
// Param1: name of file, Param 2: size in kbs
$profileImage = UploadedFile::fake()->create('test-user.jpg', 36)

// Make a http request to the endpoint with the fake file as a parameter
$this->post('/profile/update', [
    'name' => 'joe Bloggs',
    'location' => 'Leeds, UK',
    'profile_image' => $profileImage

The controller method should contain something like

$profileImageName = $request->file('profile_image')->name;
$profileImageContents = $request->file('profile_image');
$user->profile_image = Storage::disk('profile-images')->put($profileImageName, $profileImageContents);

// visit the profile page and make sure the profile picture has updated our new one


To recap we create a fake disk to store our profile pictures on. Created a fake UploadFile object setting the name, and the size of it. We then posted this to our application. Finally we navigated to the profile page and looked for the source of our newly uploaded image