【发布时间】:2021-12-24 18:44:14
【问题描述】:
我对 Laravel 的 Storake Faker 有疑问。我很难让我的代码正常工作。现在可以了,但我不是很了解 Storake Faker 的原理。
您可以在下面看到我的工作代码的简短版本:setUp 函数创建一个 Storake 假文件和一个文件。然后将文件的路径存储到数据库中。
之后,它调用存储库中的一个函数,该函数检查路径是否存在。我不允许向您展示该代码,但无论如何都没有关系,因为它正在工作;)
use WithoutMiddleware;
use DatabaseTransactions;
protected $file;
protected function setUp(): void
{
parent::setUp();
$path = 'protocols';
Storage::fake($path);
$this->file = UploadedFile::fake()->createWithContent(
'protocol.html',
'Import gestartet am: 03.09.2019 10:54:13'
)->store($path);
factory(Protocol::class)->create([
'partner_id' => 1,
'user_id' => 1,
'path' => $this->file
]);
}
/** @test */
public function path_exists()
{
//Called function returns true
$path_exists = functionCall('protocols/Test.pdf');
$this->assertTrue($path_exists);
$path_exists = functionCall('protocols/Test2.pdf');
$this->assertTrue($path_exists);
$path_exists = functionCall('protocols/Test3.pdf');
$this->assertTrue($path_exists);
}
/** @test */
public function path_does_not_exist()
{
//Called function throws an Exception
$this->expectException(Exception::class);
$this->expectExceptionMessage('file_not_found');
$path_exists = functionCall('protocols/XY.pdf');
$this->expectException(Exception::class);
$this->expectExceptionMessage('file_not_found');
$path_exists = functionCall('protocols/XY2.pdf');
}
protected function tearDown(): void
{
Storage::delete($this->file);
parent::tearDown();
}
嗯,到目前为止一切顺利。但是在我的测试之后,我必须手动删除创建的文件,就像你在 tearDown 方法中看到的那样。
我们来回答我的问题。我读了很多帖子,存储伪造者不会自行删除创建的文件。但为什么不呢?我的意思是,当我必须在测试后手动删除文件时,我还要创建一个 Storage fake。我真的不明白。
还是我理解有误,可以让 Storage Faker 自动删除文件?
编辑:: 解决方案:
use WithoutMiddleware;
use DatabaseTransactions;
protected $file;
protected function setUp(): void
{
parent::setUp();
$path = 'local';
Storage::fake($path);
$this->file = UploadedFile::fake()->createWithContent(
'protocol.html',
'Import gestartet am: 03.09.2019 10:54:13'
)->store($path);
factory(Protocol::class)->create([
'partner_id' => 1,
'user_id' => 1,
'path' => $this->file
]);
}
/** @test */
public function path_exists()
{
//Called function returns true
$path_exists = functionCall('protocols/Test.pdf');
$this->assertTrue($path_exists);
$path_exists = functionCall('protocols/Test2.pdf');
$this->assertTrue($path_exists);
$path_exists = functionCall('protocols/Test3.pdf');
$this->assertTrue($path_exists);
}
/** @test */
public function path_does_not_exist()
{
//Called function throws an Exception
$this->expectException(Exception::class);
$this->expectExceptionMessage('file_not_found');
$path_exists = functionCall('protocols/XY.pdf');
$this->expectException(Exception::class);
$this->expectExceptionMessage('file_not_found');
$path_exists = functionCall('protocols/XY2.pdf');
}
我将磁盘从“协议”更改为“本地”。 'protocols' 只是磁盘 'local' 中的一个路径,而不是磁盘本身。
在这个小改动之后,我可以删除 tearDown 函数,因为现在它会删除测试后创建的文件
【问题讨论】: