She*_*eph 6 php laravel laravel-5.6
有没有办法使用 LaravelStorage::fake()方法模拟文件?
我已经使用https://laravel.com/docs/5.7/mocking#storage-fake作为我测试的基础,它适用于上传。但是我的下载测试很难看,因为我每次都必须先使用模拟上传运行我的上传路线UploadedFile::fake()->image('avatar.jpg')。有没有办法跳过那部分并模拟文件直接存在于假存储系统中?
public function testAvatarUpload()
{
Storage::fake('avatars');
// This is the call I would like to change into a mocked existing uploaded file
$uploadResponse = $this->json('POST', '/avatar', [
'avatar' => UploadedFile::fake()->image('avatar.jpg')
]);
// Download the first avatar
$response = $this->get('/download/avatar/1');
$response->assertStatus(200);
}
Run Code Online (Sandbox Code Playgroud)
我可能来晚了。但想帮助访问此问题的其他人提供实施它的想法。
这是一个带有一些断言的示例。
<?php
namespace Tests\Feature\Upload;
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class SampleDownloadTest extends TestCase
{
/**
* @test
*/
public function uploaded_file_downloads_correctly()
{
//keep a sample file inside projectroot/resources/files folder
//create a file from it
$exampleFile = new File(resource_path('files/test-file.png'))
//copy that file to projectroot/storage/app/uploads folder
Storage::putFileAs('/uploads', $exampleFile, 'test-file.png');
//make request to file download url to get file
$response = $this->get("/files/file/download/url");
//check whethe response was ok
$response->assertOk();
$response->assertHeader('Content-Type', 'image/png')
//check whether file exists in path
Storage::assertExists('/uploads/test-file.png');
//do some more assertions.....
//after test delete the file from storage path
Storage::delete('uploads/test-file.png');
//check whether file was deleted
Storage::assertMissing('/uploads/test-file.png');
}
}
Run Code Online (Sandbox Code Playgroud)
是的,你可以使用 Laravel 的假文件存储功能(嘲笑):
use Illuminate\Http\UploadedFile;
$file = UploadedFile::fake()->create('filename.ext', $sizeInKb)->store('filename.ext');
Run Code Online (Sandbox Code Playgroud)
如果您想创建具有特定内容的文本/csv 文件,您可以使用以下命令:
use Illuminate\Http\UploadedFile;
$header = 'a,b,c';
$row1 = 'x,y,z';
$row2 = 's,f,t';
$row3 = 'r,i,o';
$content = implode("\n", [$header, $row1, $row2, $row3]);
$file = UploadedFile::fake()->createWithContent('filename.ext', $content)->store('filename.ext');
Run Code Online (Sandbox Code Playgroud)
您可以在中找到此方法的定义Illuminate\Http\Testing\FileFactory