เกริ่นนำ
Unit Test คือการทดสอบหน่วยเล็กที่สุดของโปรแกรม เช่น ฟังก์ชันหรือ method เพื่อให้มั่นใจว่าทำงานถูกต้อง Laravel มาพร้อมกับ PHPUnit ซึ่งเป็น testing framework ที่ใช้กันอย่างแพร่หลายใน PHP โดยสามารถเขียนและรันทดสอบได้ง่ายผ่าน Artisan
บทนี้จะแนะนำการสร้าง unit test สำหรับ class หรือ function ธรรมดา และวิธีตรวจสอบผลการทำงาน
การสร้าง Test Class
1 | php artisan make:test MathHelperTest |
จะได้ไฟล์ที่ tests/Feature/MathHelperTest.php
หากต้องการให้สร้างแบบ Unit (ไม่โหลด Laravel framework เต็ม):
1 | php artisan make:test MathHelperTest --unit |
ตัวอย่างฟังก์ชันที่จะทดสอบ
1 2 3 4 5 6 | // app/Helpers/MathHelper.php class MathHelper { public static function add($a, $b) { return $a + $b; } } |
ตัวอย่าง Test Case
1 2 3 4 5 6 7 8 9 10 11 | use Tests\TestCase; use App\Helpers\MathHelper; class MathHelperTest extends TestCase { public function test_addition() { $result = MathHelper::add(2, 3); $this->assertEquals(5, $result); } } |
การรันทดสอบ
1 2 3 | php artisan test # หรือ vendor/bin/phpunit |
การตั้งชื่อและจัดกลุ่ม Test
- ใช้
test_
นำหน้าเมธอด - หรือใช้ annotation
@test
- สามารถใช้
--filter
เพื่อรันเฉพาะบาง test ได้
Laravel แยก test เป็น 2 โฟลเดอร์:
Feature/
(ทดสอบรวมหลายระบบ) และUnit/
(เฉพาะ logic)