How to mock storage file download in laravel?

by mallory_cormier , in category: PHP Frameworks , 10 days ago

How to mock storage file download in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 10 days ago

@mallory_cormier 

To mock storage file download in Laravel, you can use the Storage facade along with a mock object in your test class. Here's an example of how you can mock a file download from the storage disk in a Laravel test:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
use IlluminateSupportFacadesStorage;
use IlluminateHttpFile;
use IlluminateSupportFacadesStorage;
use IlluminateSupportFacadesStorage;
use Mockery;

public function testStorageFileDownload()
{
    // Mock the Storage facade
    Storage::shouldReceive('download')->once()->andReturnUsing(function ($path, $name, $headers) {
        return response()->download(storage_path('app/public/' . $path), $name, $headers);
    });

    // Perform the request that triggers the file download
    $response = $this->get('/download-file');

    // Assert that the response is a successful download
    $response->assertStatus(200);
    $response->assertHeader('Content-Disposition', 'attachment; filename=example.jpg');
}


In this example, we mock the Storage::download method to return a response that simulates a file download. We then make a request to a route that triggers the file download and assert that the response is successful and the expected file is downloaded.


Remember to include any necessary use statements and dependencies as needed.