Testing với Pest/PHPUnit: feature test, fake, E2E, architecture test
Bộ test mà team tin tưởng: feature test gọi HTTP thật với database thật, fake cho queue/mail/HTTP/storage, factory và state, test Livewire/Inertia, architecture test, E2E bằng Dusk hoặc Playwright, chạy song song nhanh trong CI.
Laravel có công cụ test thuộc loại tốt nhất trong mọi framework — không có lý do gì để repo không có test. Với nhà tuyển dụng, một repo có feature test cho quyền truy cập, race condition, webhook và CI xanh là tín hiệu mạnh hơn mọi dòng 'có kinh nghiệm unit test' trong CV. Ngược lại, test mock mọi thứ và vỡ mỗi lần refactor là dấu hiệu thiếu kinh nghiệm.
🎯 Mục tiêu học tập
- Viết feature test qua HTTP với database thật (RefreshDatabase), factory và state
- Dùng fake: Queue, Mail, Notification, Event, Http, Storage, thời gian
- Test Livewire component và trang Inertia
- Viết architecture test và mutation test để bảo vệ chất lượng
- E2E cho luồng sống còn; chạy test song song trong CI dưới 10 phút
Feature test là xương sống
uses(RefreshDatabase::class);
it('member không xem được task của tổ chức khác', function () {
$orgA = Organization::factory()->hasMembers(1)->create();
$taskOfB = Task::factory()->for(Organization::factory())->create();
actingAs($orgA->members->first())
->getJson("/api/v1/tasks/{$taskOfB->public_id}")
->assertNotFound();
});
it('tạo task và gửi thông báo cho người được gán', function () {
Notification::fake();
[$owner, $assignee] = User::factory()->count(2)->inOrganization($org = Organization::factory()->create())->create();
actingAs($owner)->postJson("/api/v1/projects/{$project->id}/tasks", ['title' => 'Viết báo cáo', 'assignee_id' => $assignee->id])
->assertCreated()
->assertJsonPath('data.title', 'Viết báo cáo');
Notification::assertSentTo($assignee, TaskAssigned::class);
expect(Task::count())->toBe(1);
});
- Dùng cùng loại database với production trong test (MySQL/PostgreSQL qua Docker/service CI) — SQLite in-memory nhanh nhưng khác hành vi (khoá, JSON, kiểu dữ liệu).
- Factory với state có tên (
->overdue(),->assignedTo($u)) giúp test đọc như đặc tả. - Test hành vi qua HTTP/Action công khai, không test chi tiết cài đặt.
Fake và kiểm soát thời gian
Http::fake([
'api.stripe.com/*' => Http::sequence()->push(['error' => 'timeout'], 503)->push(['id' => 'ch_1'], 200),
]);
Http::preventStrayRequests(); // test fail nếu gọi ra Internet thật
Queue::fake(); Queue::assertPushed(SendInvoiceEmail::class, fn ($job) => $job->invoiceId === $invoice->id);
Storage::fake('s3');
Event::fake([TaskCompleted::class]);
$this->travelTo(now()->addDays(8)); // test logic deadline, hết hạn token, subscription
Fake những gì nằm ngoài hệ thống của bạn (API đối tác, mail, file); không mock Eloquent hay code của chính bạn.
Test Livewire, Inertia, architecture
// Livewire
Livewire::actingAs($member)->test(TaskList::class, ['projectId' => $project->id])
->set('newTitle', '')->call('addTask')->assertHasErrors(['newTitle' => 'required']);
// Inertia
actingAs($user)->get(route('projects.show', $project))
->assertInertia(fn (AssertableInertia $page) => $page->component('Projects/Board')->has('tasks', 3)->missing('tasks.0.internal_notes'));
// Architecture test (Pest)
arch('controllers không truy cập DB trực tiếp')->expect('App\Http\Controllers')->not->toUse('Illuminate\Support\Facades\DB');
arch('không còn debug')->expect(['dd', 'dump', 'ray', 'var_dump'])->not->toBeUsed();
arch()->preset()->laravel();
E2E, mutation testing và CI
- E2E cho 5-10 luồng sống còn (đăng ký, đăng nhập, tạo project, kéo thả, thanh toán): Laravel Dusk, hoặc Pest browser testing (dựa trên Playwright), hoặc Playwright TypeScript riêng.
- Mutation testing (
pest --mutatehoặc Infection) đo chất lượng test: sửa code (đổi>thành>=) mà test vẫn xanh = test thiếu. - Chạy song song:
php artisan test --parallel. Coverage 70-80% cho logic nghiệp vụ là hợp lý; đừng săn 100%. - Mỗi bug production sửa xong phải có test tái hiện nó.
🏋️ Bài tập thực hành
(1) Feature test cho mọi endpoint/trang chính, bao gồm IDOR, policy theo role, race condition claim task, idempotency thanh toán, webhook trùng lặp. (2) Unit test cho value object, enum transition, tính tiền. (3) Test Livewire và Inertia props (không lộ field nhạy cảm). (4) 5 architecture test cho quy ước của dự án. (5) 5 E2E cho luồng sống còn. (6) Mutation score ≥ 70% cho module Billing. (7) GitHub Actions chạy toàn bộ với MySQL/PostgreSQL + Redis service dưới 10 phút.
📚 Tài nguyên học tập
-
PestFramework test hiện đại cho PHPDocs
-
Laravel — TestingHTTP test, database, mockingDocs
-
Laravel — HTTP Client fakingHttp::fake, preventStrayRequestsDocs
-
InfectionMutation testing cho PHPDocs
✅ Tự đánh giá hoàn thành
- Feature test với database cùng loại production
- Fake mọi gọi ra ngoài, có preventStrayRequests
- Có architecture test và mutation test cho phần quan trọng
- CI chạy toàn bộ test dưới 10 phút