การ Test Upload ไฟล์ใน Laravel

Laravel มี ตัวช่วยสำหรับการทดสอบ file upload โดยอาศัย method fake()
ในคลาส UploadFile
หรือใน facade Storage
การ Fake File Upload
ตัวอย่างการใช้งานตาม Documentation ของ Laravel อธิบายตามนี้
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_avatars_can_be_uploaded()
{
Storage::fake('avatars');
$file = UploadedFile::fake()->image('avatar.jpg');
$response = $this->post('/avatar', [
'avatar' => $file,
]);
Storage::disk('avatars')->assertExists($file->hashName());
}
}
การ Fake Upload รูปภาพ
เราสามารถ fake upload รูปภาพ โดยใช้ method image(
) โดยระบุนามสกุลเป็น .jpg, หรือ .png ได้
// Fake รูปภาพประเภท jpeg
UploadedFile::fake()->image('avatar.jpg');
// Fake รูปภาพประเภท png
UploadedFile::fake()->image('avatar.png');
หากเราต้องการจำลองขนาดความกว้างและความสูงของรูปที่ upload เราสามารถระบุ Parameter เพิ่มได้ ดังนี้
UploadedFile::fake()->image('avatar.jpg', $width, $height)->size(100);
การ Fake Upload ไฟล์ PDF
ถ้าเราต้องการ Fake Upload เอกสาร pdf เราสามารถใช้ method create()
ในการจำลองไฟล์ pdf ได้
UploadedFile::fake()->create('document.pdf');
การ Fake Upload ไฟล์ Excel จริง
ในบางคร้้งเราต้องการใช้ไฟล์จริง ๆ ที่เราเตรียมไว้เพื่อใช้ทดสอบ upload ไฟล์ เช่น ทดสอบการ Import ไฟล์ จาก excel, csv หรือ .txt ไฟล์ที่เราเตรียมข้อมูลไว้แล้ว เราสามารถใช้ method createWithContent()
เพื่อดึงข้อมูลในไฟล์ที่เราเตรียมไว้เพื่อทำการทดสอบ upload ได้ ดังนี้
UploadedFile::fake()->createWithContent(
'survey_template.xlsx',
file_get_contents(base_path('tests/Feature/stub/import-template.xlsx'))
);
ดูรายละเอียดเพิ่มเติมได้จาก Laravel Documentation