gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:44:38 24 4
gpt4 key购买 nike

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

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

文件上传 Controller

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

文件系统.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'),
],
],

非常感谢帮助,谢谢。

最佳答案

使用 Storage::fake('files'),您可以伪造一个名为“files”的所谓磁盘。在您的 filesystems.php 中没有磁盘声明为"file"。

在您的 FileUploadController 中,您正在保存到“本地”磁盘上的子目录"file",因此为了使您的测试正常进行,只需伪造此磁盘:

Storage::fake('local');

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

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

在测试环境中,路径将是storage/framework/testing/disks,而不是直接低于storage/app

关于php - Laravel 5.6 测试文件上传(无法在路径 [file.txt] 找到文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49166927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com