عند إنشائك نُسخة من الصنف UploadedFile قم بتمرير القيمة true لآخر وسيط بهذا الشكل و هذا الوسيط هو وسيط بولياني يأخذ true إن كانت البيئة هي بيئة إختبارية و القيمة الإفتراضية له هي false.
$file = new UploadedFile($path, $name, filesize($path), 'image/png', null, true);
^^^^
و هذا مثال يوضح الآلية بإعتبار وجود ملف صورة بالإسم test.png بداخل مجلد tests/stubs:
<?php
class UploadTest extends TestCase
{
public function test_upload_works()
{
$stub = __DIR__.'/stubs/test.png';
$name = str_random(8).'.png';
$path = sys_get_temp_dir().'/'.$name;
copy($stub, $path);
$file = new UploadedFile($path, $name, filesize($path), 'image/png', null, true);
$response = $this->call('POST', '/upload', [], [], ['photo' => $file], ['Accept' => 'application/json']);
$this->assertResponseOk();
$content = json_decode($response->getContent());
$this->assertObjectHasAttribute('name', $content);
$uploaded = 'uploads'.DIRECTORY_SEPARATOR.$content->name;
$this->assertFileExists(public_path($uploaded));
@unlink($uploaded);
}
}
بإمكانك أيضاً النظر إلى التابع fake فهو يُساعد كثيراً في عملية إختبار رفع الملفات مثال:
<?php
class UploadTest extends TestCase
{
public function test_upload_works()
{
$this->post(
action('AttachmentController@store'),
['file' => UploadedFile::fake()->image('file.png', 600, 600)]
);
/** @var \App\Attachment $attachment */
$this->assertNotNull($attachment = Attachment::query()->first());
$this->assertFileExists($attachment->path());
@unlink($attachment->path());
}
}