Laravel 5.6测试文件上传(无法在路径[file.txt]中找到文件)

时间:2018-03-08 06:41:07

标签: php phpunit ubuntu-16.04 laravel-5.6

我是laravel的新手,我可以成功运行我的文件上传器,它成功上传我的文件,但单元测试失败,这是我的代码:

UploadTest.php

public function testUploadFile()
{
    $fileSize = 1024; // 1mb
    $fileName = 'file.txt';

    Storage::fake('files');
    $response = $this->json('POST', '/webservice/upload', [
        'file' => UploadedFile::fake()->create($fileName, $fileSize)
    ]);

    Storage::disk('files')->assertExists($fileName);
    Storage::disk('files')->assertMissing($fileName);
}

FileUploadController

public function upload(Request $request)
{
    $file = $request->file('file');
    if ($file == null) {
      return view('fileupload', 
        ['submitClickedMsg' => "Please select a file to upload."]);
    }

    $path = $file->storeAs('files', $file->getClientOriginalName(), 'local');
    return response()->json([
      'path' => $path
    ]);
}

filesystem.php

'disks' => [
        'local' => [
            'driver' => 'local',
            'root' => storage_path('app'),
        ],
        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],
    ],

非常感谢帮助,谢谢。

1 个答案:

答案 0 :(得分:8)

使用Storage::fake('files'),你会伪造一个名为'files'的所谓磁盘。在你的filesystems.php中没有声明名为'files'的磁盘。

在FileUploadController中,您将保存到“本地”磁盘上的子目录“files”,因此为了使您的测试工作,只需伪造此磁盘:

Storage::fake('local');

然后使用此磁盘进行断言:

Storage::disk('local')->assertExists('files/' . $fileName);

在测试环境中,路径将为storage/framework/testing/disks而不是storage/app以下。