Lab 08: Testing & TDD

Objective

Build a complete test suite using only PHP's built-in capabilities: a custom assertion library, test runner with pass/fail tracking, test doubles (stubs and fakes), Test-Driven Development (TDD) red-green-refactor cycle, and code coverage simulation.

Background

PHPUnit is the standard test framework, but understanding testing mechanics makes you a better PHPUnit user. PHP's assert() function is built-in but limited. This lab builds a micro test runner that mirrors PHPUnit's structure. TDD means writing the test before the implementation — the test fails (red), you write code to pass it (green), then improve the code (refactor) without breaking tests.

Time

30 minutes

Prerequisites

  • PHP Foundations Lab 09 (Error Handling)

Tools

  • Docker: zchencow/innozverse-php:latest


Lab Instructions

Step 1: Micro test framework + test doubles

💡 Test doubles have specific roles. A stub provides canned answers with no logic (always returns true, or a fixed value). A fake has a working implementation (in-memory DB instead of real DB). A spy records calls so you can verify interactions afterward. A mock has pre-programmed expectations (PHPUnit's expects()->with()) and fails if not called correctly. Use the simplest double that satisfies the test.

📸 Verified Output:


Summary

Concept
Purpose

assertEquals

Strict value comparison (===)

assertThrows

Verify exceptions are thrown

Stub

Pre-configured return values

Spy

Record calls for assertion

Fake

Lightweight working implementation

TDD cycle

Red → Green → Refactor

Further Reading

Last updated