PHPUnit(單元測試)

測試特性

  1. Laravel 會自動將測試環境變數 APP_ENV 設為 testing
  2. SessionCache 預設會使用 array 驅動(記憶體內,不會持久儲存)
  3. 測試設定依據 phpunit.xml 設定檔進行執行

測試準備

建立測試資料庫

  1. 匯出要測試的資料表結構(無需資料內容)
  2. 使用 MySQL 建立一個測試資料庫並匯入資料表結構

設定 .env.testingphpunit.xml 資料庫環境變數

選項一:建立 .env.testing

DB_DATABASE=your_test_database

選項二:設定 phpunit.xml

<php>
    <env name="DB_DATABASE" value="your_test_database"/>
</php>

執行 PHPUnit 測試

./vendor/bin/phpunit

建立測試檔案結構

建立測試目錄與定義測試套件:

<testsuites>
    <testsuite name="Unit">
        <directory suffix="Test.php">tests/Unit</directory>
    </testsuite>
    <testsuite name="Feature">
        <directory suffix="Test.php">tests/Feature</directory>
    </testsuite>
</testsuites>

Controller 測試範例

測試目的說明

本測試用於驗證「使用者資料更新」功能是否正常:

  • 在測試開始前,先建立一個假使用者(fakeUser
  • 對此使用者進行密碼更新操作,模擬資料更新行為
  • 發送 POST 請求到 update-user 路由(可改為實際應用的 API 路由)
  • 驗證回應 HTTP 狀態碼是否為 200(成功)

此測試可確保使用者資料更新流程正常執行,且 Controller 路由有正確回應。


範例程式碼:tests/Feature/Controller/UserTest.php

<?php

namespace Tests\Feature\Controller;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
use App\Models\User;

class UserTest extends TestCase
{
    use RefreshDatabase;

    private $fakeUser;

    protected function setUp(): void
    {
        parent::setUp();

        // 建立測試用假使用者
        $this->fakeUser = User::factory()->create([
            'name' => 'jack',
            'password' => bcrypt('123456'),
        ]);
    }

    public function testUpdateUser()
    {
        // 更新密碼資料
        $updateData = [
            'password' => bcrypt('654321'),
        ];

        // 模擬更新使用者密碼
        $this->fakeUser->update($updateData);

        // 發送 POST 請求測試 Controller 路由
        $response = $this->post('/update-user', [
            'key' => 'value',
        ]);

        // 驗證 HTTP 狀態碼為 200(成功)
        $response->assertStatus(200);
    }
}