有没有办法使用Laravel Storage::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);
}
我可能会迟到。但是想帮助其他人访问这个问题来提出实现它的想法。
这是一个包含一些断言的示例。
<?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');
}
}
您可以直接创建新文件或复制特定的测试文件,例如:
use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
// for simple text files or if the content doesn't matter
Storage::disk('avatars')->put('avatar.jpg', 'some non-jpg content');
// if you need a specific file for your test
$file = new File(base_path('tests/resources/avatar.jpg'));
Storage::disk('avatars')->putFileAs('/', $file, 'avatar.jpg');
后一个函数将获取$file
并将其以给定名称avatar.jpg
复制到磁盘/
上的给定目录avatars
。你可以阅读更多关于它in the official documentation。
你可以用来解决这个问题的是固定装置。 Laravel的测试框架本质上是PHPUnit,所以我认为没有理由说它不起作用。
像这样定义你的测试:
use Tests\TestCase;
class ExampleTest extends TestCase {
protected function setUp() {
parent::setUp();
Storage::fake('avatars');
$uploadResponse = $this->json('POST', '/avatar', [
'avatar' => UploadedFile::fake()->image('avatar.jpg')
]);
}
protected function tearDown() {
parent::tearDown();
}
public function testAvatarUpload() {
// Download the first avatar
$response = $this->get('/download/avatar/1');
$response->assertStatus(200);
}
}
setUp
和tearDown
分别在课堂上的每次测试之前和之后被调用。因此,在每种测试方法之前,setUp
将擦除avatars
假磁盘并运行请求。由于测试后无事可做(因为Storage::fake()
替换了磁盘,如果它已经存在),该方法为空;我把它留在这里纯粹是为了让这个例子完整。
关于PHPunit的这个功能,有一些非常好的文档on here。
关于把文件放在那里,一旦你的setUp
正常工作,没有什么能阻止你把文件扔到它上面。