PHP เขียนเทสต์ด้วย PHPUnit



เทสต์อัตโนมัติคือโค้ดที่ตรวจว่าโค้ดอื่นทำงานถูก รันได้ในไม่กี่วินาที ทำให้กล้าแก้/refactor โดยไม่กลัวพังเงียบ ๆ

ติดตั้ง

composer require --dev phpunit/phpunit
./vendor/bin/phpunit --version
PHPUnit 11.4.3 by Sebastian Bergmann and contributors.

สร้าง phpunit.xml ที่ราก:

<?xml version="1.0"?>
<phpunit bootstrap="vendor/autoload.php"
         colors="true"
         cacheDirectory=".phpunit.cache">
    <testsuites>
        <testsuite name="default">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
    <source>
        <include>
            <directory>src</directory>
        </include>
    </source>
</phpunit>

โค้ดที่จะทดสอบ

src/PriceCalculator.php:

<?php
declare(strict_types=1);

namespace App;

class PriceCalculator
{
    public function __construct(private float $vatRate = 0.07) {}

    public function withVat(float $price): float
    {
        if ($price < 0) {
            throw new \InvalidArgumentException('ราคาติดลบไม่ได้');
        }
        return round($price * (1 + $this->vatRate), 2);
    }

    public function discount(float $price, int $percent): float
    {
        if ($percent < 0 || $percent > 100) {
            throw new \InvalidArgumentException('ส่วนลดต้องอยู่ 0–100');
        }
        return round($price * (1 - $percent / 100), 2);
    }
}

test class แรก

tests/PriceCalculatorTest.php (ตั้ง "Tests\\": "tests/" ใน autoload-dev แล้ว composer dump-autoload):

<?php
declare(strict_types=1);

namespace Tests;

use App\PriceCalculator;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Attributes\DataProvider;

final class PriceCalculatorTest extends TestCase
{
    private PriceCalculator $calc;

    protected function setUp(): void
    {
        $this->calc = new PriceCalculator(vatRate: 0.07);
    }

    public function test_adds_seven_percent_vat(): void
    {
        $this->assertSame(107.0, $this->calc->withVat(100));
    }

    public function test_rounds_to_two_decimals(): void
    {
        $this->assertSame(115.56, $this->calc->withVat(108.0));
    }

    public function test_throws_on_negative_price(): void
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->calc->withVat(-1);
    }

    public function test_zero_price_is_zero(): void
    {
        $this->assertSame(0.0, $this->calc->withVat(0));
    }
}

โครงสร้าง:

  • test class ลงท้าย Test, extends TestCase, มักใส่ final
  • เมธอดทดสอบขึ้นต้น test หรือใส่ attribute #[Test]
  • setUp() รันก่อนทุกเมธอดทดสอบ — สร้างของสดใหม่ทุกครั้ง ไม่ให้เทสต์กวนกัน

รันเทสต์

./vendor/bin/phpunit
PHPUnit 11.4.3 by Sebastian Bergmann and contributors.

....                                                                4 / 4 (100%)

Time: 00:00.018, Memory: 8.00 MB

OK (4 tests, 4 assertions)

จุด . = ผ่าน, F = fail, E = error ทำให้ fail ดูข้อความ:

1) Tests\PriceCalculatorTest::test_adds_seven_percent_vat
Failed asserting that 108.0 is identical to 107.0.

/path/tests/PriceCalculatorTest.php:20

assertion ที่ใช้บ่อย

<?php
$this->assertSame(107.0, $actual);        // === (ชนิดต้องตรงด้วย) — ใช้ตัวนี้เป็นหลัก
$this->assertEquals(107, $actual);        // == (ไม่สนชนิด) — เลี่ยงถ้าทำได้
$this->assertTrue($condition);
$this->assertFalse($condition);
$this->assertNull($value);
$this->assertCount(3, $array);
$this->assertContains('a', $array);
$this->assertArrayHasKey('name', $data);
$this->assertInstanceOf(User::class, $obj);
$this->assertStringContainsString('error', $message);
$this->assertGreaterThan(0, $value);
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('ยอดไม่พอ');

นิยมใช้ assertSame มากกว่า assertEquals เพราะจับบั๊กชนิดข้อมูล (คืน "107" แทน 107.0)

data provider — ทดสอบหลายเคสด้วยเมธอดเดียว

<?php
#[DataProvider('discountCases')]
public function test_discount(float $price, int $percent, float $expected): void
{
    $this->assertSame($expected, $this->calc->discount($price, $percent));
}

public static function discountCases(): array
{
    return [
        'ลด 0%'   => [100.0, 0, 100.0],
        'ลด 10%'  => [100.0, 10, 90.0],
        'ลด 50%'  => [200.0, 50, 100.0],
        'ลด 100%' => [80.0, 100, 0.0],
    ];
}

provider เป็น static คืนอาร์เรย์ของอาร์เรย์ (แต่ละตัวคือชุดพารามิเตอร์) key ของอาร์เรย์นอกเป็นชื่อเคสที่โผล่ตอน fail

✓ ลด 0%
✓ ลด 10%
✓ ลด 50%
✓ ลด 100%

เขียนเทสต์ยังไงให้มีประโยชน์

  • ทดสอบพฤติกรรม ไม่ใช่ implementation — เทสต์ควรผ่านต่อไปแม้เรา refactor ข้างในคลาส
  • ตั้งชื่อเมธอดให้เป็นประโยค — test_withdraw_fails_when_balance_too_low อ่านแล้วรู้ว่าทดสอบอะไร
  • 1 เทสต์ = 1 พฤติกรรม — fail แล้วรู้ทันทีว่าอะไรพัง
  • ทดสอบ edge case — 0, ค่าติดลบ, อาร์เรย์ว่าง, null, ค่าสูงสุด
  • Arrange–Act–Assert — เตรียมข้อมูล, เรียกสิ่งที่ทดสอบ, ตรวจผล (เว้นบรรทัดแบ่ง 3 ส่วน)

เรื่องที่คนมักพลาด

  • ใช้ assertEquals ทุกที่ — พลาดบั๊กชนิด เช่นฟังก์ชันคืนสตริง "107" แทน float ใช้ assertSame
  • สลับลำดับ argument — PHPUnit คือ assertSame($expected, $actual) (คาดหวังก่อน) สลับแล้วข้อความ fail จะกลับหัว
  • เทสต์พึ่งพากัน — เทสต์ A ต้องรันก่อน B ไม่งั้นพัง = ออกแบบผิด แต่ละเทสต์ต้องรันเดี่ยว ๆ ได้ ใช้ setUp() สร้างของใหม่
  • setUp() แต่พิมพ์เป็น setup() หรือ SetUp() — ต้องเป๊ะ setUp (PHPUnit 10+ เตือนถ้าไม่มี void return type)
  • ไม่รันเทสต์บ่อย — เทสต์ที่ไม่รันก็เหมือนไม่มี รันทุกครั้งก่อน commit (หรือให้ CI รัน)
  • data provider ไม่ static — PHPUnit 10+ บังคับ static ไม่งั้น error

สรุป

  • composer require --dev phpunit/phpunit + phpunit.xml ที่ราก
  • test class ลงท้าย Test, extends TestCase, เมธอดขึ้นต้น test
  • setUp() สร้างของสดก่อนทุกเทสต์ให้อิสระต่อกัน
  • assertSame($expected, $actual) เป็นหลัก, expectException() สำหรับเคสที่ต้อง throw
  • #[DataProvider('method')] + provider แบบ static ทดสอบหลายเคสด้วยเมธอดเดียว
  • รัน ./vendor/bin/phpunit (หรือ composer test) บ่อย ๆ

บทถัดไปว่าด้วยมาตรฐานโค้ด (PSR-12) และเครื่องมือวิเคราะห์แบบสถิต — PHP-CS-Fixer และ PHPStan ที่จับบั๊กก่อนรัน