首页 > 解决方案 > 如何在 Laravel 中模拟存储文件下载

问题描述

我有一个控制器方法,允许用户使用存储门面从 S3 下载文件:

public function download(Export $export): StreamedResponse
{
    return Storage::disk('s3-data-exports')->download($export->path);
}

我正在尝试为此创建一个测试,但遇到了磁盘方法应该返回的问题:

public function testClientCanDownloadExport()
{
    Storage::fake('s3-data-exports');

    $export = factory(Export::class)->create();

    $file = new File(base_path('tests/_data/ricardo/IntakeDataExport.csv'));
    
    Storage::shouldReceive('disk')
        ->with('s3-data-exports')
        ->andReturn() // <--- what goes in here?
        ->shouldReceive('download')
        ->andReturn($file);

    $this->json('GET', route('exports.download', $export->id))
        ->assertStatus(200);
}

disk 方法应该返回什么才能使链接工作并且下一个 shouldReceive 正确运行?

标签: phplaravellaravel-7

解决方案


我认为你可以这样做:

public function testClientCanDownloadExport()
{
    $storage = Storage::fake('s3-data-exports');

    // Create fake file
    $file = UploadedFile::fake()->create('IntakeDataExport.csv', 100);

    // Store fake file on the s3-data-exports disk
    $filePath = $file->store('csv', 's3-data-exports');

    // Create export and set the path attribute to match the saved file's path
    $export = factory(Export::class)->create(['path' => $filePath]);

    Storage::shouldReceive('disk')
        ->with('s3-data-exports')
        ->andReturn($storage)
        ->shouldReceive('download')
        ->andReturn($file);

    $this->get(route('exports.download', $export->id))
        ->assertStatus(200);
}

推荐阅读