【问题标题】:How to mock Storage file download in Laravel如何在 Laravel 中模拟存储文件下载
【发布时间】:2021-05-15 15:44:34
【问题描述】:

我有一个控制器方法,允许用户使用存储门面从 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 正常运行?

【问题讨论】:

  • 方法disk($name = null)返回一个实现接口\Illuminate\Contracts\Filesystem\Filesystem的类的实例

标签: php laravel laravel-7


【解决方案1】:

我认为你可以这样做:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 2017-08-16
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多