The Analogy: The Electrical Appliance Testing Bench
In a testing laboratory, every appliance that comes off a line is put through a fixed battery of checks before it can be certified. Each check is written down in advance: earth continuity below a stated resistance, insulation above a stated value, a load test drawing the expected current. The point is that "expected" is defined before the appliance ever arrives. The tester is not squinting at a reading and deciding whether it looks healthy; they are comparing it against a number agreed in the specification.
Each check yields a blunt verdict -- pass or fail -- with the measured value recorded beside the threshold it was judged against. A competent tester never writes "seems fine." When a unit fails its insulation check, the report says exactly which check failed and what the reading was, so the fault can be located without repeating every other test. A batch of fifty appliances produces fifty verdicts, and a single failure among them does not obscure the other forty-nine passes.
Critically, every appliance is tested on a freshly reset bench. The jig is returned to its starting position, any residual charge is bled off, and the previous unit's leads are cleared before the next is clamped in. This isolation means a fault or a leftover setting from one unit cannot leave the bench in a state that makes the next unit pass or fail dishonestly. The preparation runs before each test and the reset runs after it, every single time.
The laboratory's whole value collapses if the thresholds are wrong or the checks do not measure what actually matters. A test that can never fail -- because its threshold is set impossibly loose, or because it records an impression rather than a measurement -- gives false confidence. The certificate then says "tested" while nothing was truly verified, and a green report from checks that cannot fail is more dangerous than no report at all, because people trust it and stop looking.
Syntax or Core Structure
PHPUnit is the de facto testing framework for PHP. It is not bundled with this runtime, so the harness below is a deliberately stripped-down stand-in that shows the same shape: a test-case base class, assertion methods that throw on failure, and a runner that reports pass or fail for each test. In a real project you install PHPUnit through Composer, extend PHPUnit\\Framework\\TestCase, write methods named test..., call assertions such as $this->assertSame(...), and run the suite with vendor/bin/phpunit.
<?php
declare(strict_types=1);
final class Stack {
private array $items = [];
public function push(int $n): void { $this->items[] = $n; }
public function pop(): int {
if ($this->items === []) {
throw new RuntimeException('pop from empty stack');
}
return array_pop($this->items);
}
public function size(): int { return count($this->items); }
public function isEmpty(): bool { return $this->items === []; }
}
abstract class TestCase {
protected function assertSame($expected, $actual, string $msg = ''): void {
if ($expected !== $actual) {
throw new RuntimeException($msg !== '' ? $msg : 'assertSame failed');
}
}
protected function assertTrue(bool $cond, string $msg = ''): void {
if ($cond !== true) {
throw new RuntimeException($msg !== '' ? $msg : 'assertTrue failed');
}
}
public function runAll(): void {
$pass = 0; $fail = 0;
foreach (get_class_methods($this) as $m) {
if (!str_starts_with($m, 'test')) {
continue;
}
try {
$this->$m();
echo "$m: PASS\n";
$pass++;
} catch (Throwable $e) {
echo "$m: FAIL (" . $e->getMessage() . ")\n";
$fail++;
}
}
echo "--- $pass passed, $fail failed ---\n";
}
}
final class StackTest extends TestCase {
public function testNewStackIsEmpty(): void {
$s = new Stack();
$this->assertTrue($s->isEmpty());
}
public function testPushIncreasesSize(): void {
$s = new Stack();
$s->push(10);
$s->push(20);
$this->assertSame(2, $s->size());
}
public function testPopReturnsLast(): void {
$s = new Stack();
$s->push(10);
$s->push(20);
$this->assertSame(20, $s->pop());
}
}
(new StackTest())->runAll();
Output:
testNewStackIsEmpty: PASS
testPushIncreasesSize: PASS
testPopReturnsLast: PASS
--- 3 passed, 0 failed ---
The Stack is the code under test; StackTest is the test case. Each test method sets up a known situation, exercises the class, and asserts an exact expected result -- assertSame(2, $s->size()) says the size must be precisely two, not merely "about right." The runner finds every method whose name starts with test, runs it, and turns a thrown assertion into a FAIL while a clean return is a PASS. Real PHPUnit does exactly this discovery-and-report cycle, only with far richer assertions and output.
Technical Depth: Assertions, Exceptions, and Fixtures
Choosing the right assertion
PHPUnit ships dozens of assertions; a handful cover most tests. The most important distinction is between the strict and loose equality checks.
| Assertion | Passes when | Note |
|---|---|---|
assertSame($e, $a) | $e === $a | Strict: type and value must match |
assertEquals($e, $a) | $e == $a | Loose: compares value only |
assertTrue($c) | $c === true | Must be exactly true |
assertNull($v) | $v === null | Must be exactly null |
assertCount($n, $a) | count($a) === $n | Size of a countable |
expectException($cls) | the code throws $cls | Declared before the call |
The difference between assertSame and assertEquals is the difference between === and ==, and it decides whether a wrong type sneaks past your test.
<?php
declare(strict_types=1);
$cases = [
['1 vs 1 (int)', 1, 1],
['1 vs "1"', 1, '1'],
['0 vs false', 0, false],
['1.0 vs 1', 1.0, 1],
];
foreach ($cases as [$label, $a, $b]) {
$s = ($a === $b) ? 'same' : 'diff';
$e = ($a == $b) ? 'equal' : 'notequal';
echo "$label -> assertSame:$s assertEquals:$e\n";
}
Output:
1 vs 1 (int) -> assertSame:same assertEquals:equal
1 vs "1" -> assertSame:diff assertEquals:equal
0 vs false -> assertSame:diff assertEquals:equal
1.0 vs 1 -> assertSame:diff assertEquals:equal
Every row except the first is judged the same by assertEquals but different by assertSame. If your function is supposed to return the integer 1 and a refactor makes it return the string "1", assertEquals stays green while assertSame catches the regression. Prefer assertSame unless you have a specific reason to ignore type.
Testing that code throws
A test must also pin down failure behaviour: that invalid input raises the right exception. In PHPUnit you declare $this->expectException(...) before calling the code; the pattern below shows the same idea with a helper.
<?php
declare(strict_types=1);
final class Account {
private int $balance = 0;
public function deposit(int $n): void {
if ($n <= 0) {
throw new InvalidArgumentException('deposit must be positive');
}
$this->balance += $n;
}
public function balance(): int { return $this->balance; }
}
function expectException(string $class, callable $fn): string {
try {
$fn();
return "no exception (expected $class)";
} catch (Throwable $e) {
return $e instanceof $class
? "threw $class as expected"
: "wrong type: " . get_class($e);
}
}
$a = new Account();
echo expectException(InvalidArgumentException::class, fn() => $a->deposit(-5)), "\n";
$a->deposit(100);
echo 'balance: ', $a->balance(), "\n";
Output:
threw InvalidArgumentException as expected
balance: 100
Wrapping the call in a closure lets the helper run it inside a try and check that the thrown type matches. The test asserts two things: that a negative deposit is rejected with InvalidArgumentException, and that a valid deposit still updates the balance. Testing the failure path is as important as testing the happy path, because that is where guards silently rot.
Fixtures: setUp and isolation
The setUp method runs before each test and builds a fresh subject, so no test inherits state from the one before it -- exactly the freshly reset bench. A matching tearDown runs after each test to release resources such as a database connection or a temporary file. Because setUp runs anew for every method, one test mutating the subject cannot make another pass or fail dishonestly; the isolation is what lets you trust a green suite.
Real World Example: A Cart Test Suite
A shopping Cart keeps line items as name, price in cents, and quantity, and can report its subtotal and item count. Alongside it sits a pure applyPercent function that takes a discount off a price and rounds to the nearest cent. The suite below tests all of it: two stateful tests that rely on a fresh cart from setUp, and one test that drives the rounding function across several input rows.
<?php
declare(strict_types=1);
final class Cart {
private array $lines = [];
public function add(string $name, int $cents, int $qty = 1): void {
$this->lines[] = ['name' => $name, 'cents' => $cents, 'qty' => $qty];
}
public function subtotal(): int {
$t = 0;
foreach ($this->lines as $l) {
$t += $l['cents'] * $l['qty'];
}
return $t;
}
public function count(): int {
$n = 0;
foreach ($this->lines as $l) {
$n += $l['qty'];
}
return $n;
}
}
function applyPercent(int $cents, int $percent): int {
return (int) round($cents * (100 - $percent) / 100);
}
abstract class TestCase {
protected function assertSame($e, $a, string $m = ''): void {
if ($e !== $a) {
throw new RuntimeException($m !== '' ? $m : 'expected ' . var_export($e, true) . ' got ' . var_export($a, true));
}
}
protected function setUp(): void {}
public function runAll(): void {
$pass = 0; $fail = 0;
foreach (get_class_methods($this) as $m) {
if (!str_starts_with($m, 'test')) {
continue;
}
$this->setUp();
try {
$this->$m();
echo "$m: PASS\n";
$pass++;
} catch (Throwable $e) {
echo "$m: FAIL (" . $e->getMessage() . ")\n";
$fail++;
}
}
echo "--- $pass passed, $fail failed ---\n";
}
}
final class CartTest extends TestCase {
private Cart $cart;
protected function setUp(): void {
$this->cart = new Cart();
}
public function testEmptyCartTotalsZero(): void {
$this->assertSame(0, $this->cart->subtotal());
}
public function testSubtotalSumsQuantities(): void {
$this->cart->add('Pen', 150, 3);
$this->cart->add('Pad', 500, 1);
$this->assertSame(950, $this->cart->subtotal());
$this->assertSame(4, $this->cart->count());
}
public function testDiscountRoundsToNearestCent(): void {
foreach ([[1000, 10, 900], [999, 10, 899], [333, 33, 223]] as [$in, $pct, $out]) {
$this->assertSame($out, applyPercent($in, $pct), "percent $pct on $in");
}
}
}
(new CartTest())->runAll();
Output:
testEmptyCartTotalsZero: PASS
testSubtotalSumsQuantities: PASS
testDiscountRoundsToNearestCent: PASS
--- 3 passed, 0 failed ---
The setUp method assigns a brand-new Cart to $this->cart before every test, so testEmptyCartTotalsZero sees an empty cart even though testSubtotalSumsQuantities adds items. Without that reset, the order the runner happened to pick would leak state between tests and the empty-cart assertion could fail for no real reason. This is the reset bench made concrete: the same starting condition, guaranteed, for each check.
The first two tests pin down exact numbers. Three pens at 150 cents and one pad at 500 give a subtotal of 950 cents and a count of four items, and assertSame insists on those precise integers. The third test reuses one assertion across a table of rows: a ten percent discount on 1000 cents is 900, on 999 rounds to 899, and a thirty-three percent discount on 333 rounds to 223. Feeding several input-and-expected rows through one check is the essence of a data provider.
Every assertion here compares against a value computed by hand in advance, never against the code's own output, which is what keeps the test honest. If applyPercent had a sign slip and took the discount amount rather than the remainder -- computing percent instead of 100 - percent -- then a ten percent discount on 1000 cents would return 100 rather than 900, and the first row would fail loudly, pointing straight at the broken arithmetic. That is the whole purpose: a deliberate, precomputed expectation that a regression cannot quietly satisfy.
The design flaw is in cramming three cases into a single testDiscountRoundsToNearestCent method. Because the loop shares one test method, a failure on any row aborts the remaining rows and the whole method counts as one failure, so you lose the per-row verdict a real data provider gives -- PHPUnit runs each provided row as its own named test, reporting exactly which inputs failed. The home-grown harness also stops at the first failing assertion within a method, offers no diff output, and cannot detect a "risky" test that asserts nothing at all. These are precisely the reasons to install PHPUnit rather than hand-roll a runner: the shape is easy to reproduce, but the reporting, isolation guarantees, and tooling around it are not.
Common Mistakes
- Testing the implementation instead of the behaviour. Asserting on private internals or the exact SQL a method builds makes tests break on every harmless refactor. Assert on observable outputs -- return values, thrown exceptions, and visible side effects.
- Using
assertEqualswhereassertSameis meant. Loose equality lets the string"1"pass for the integer1, so a type regression slips by green. Reach forassertSameby default and only relax it deliberately.
- Sharing state between tests. Building the subject once in a property and mutating it across tests makes results depend on run order. Rebuild it in
setUpso each test starts from the same clean state.
- Writing a test that asserts nothing. A method that exercises code but never calls an assertion always "passes," giving false coverage. Every test needs at least one assertion that is capable of failing.
- Asserting against the code's own output. Capturing what a function returns and asserting it equals itself proves nothing. Expected values must be computed independently, by hand, before the code runs.
- Only testing the happy path. Skipping the error cases -- empty input, negative numbers, missing keys -- leaves the guards untested, which is exactly where bugs hide. Test the failure paths on purpose.
- Depending on real time, randomness, or the network. A test that calls
time(),rand(), or a live API is flaky by construction. Inject a fixed clock, a seed, or a fake so the result is deterministic.
- Bundling many checks into one giant test. When unrelated assertions share a method, the first failure hides the rest and the method name cannot describe what actually broke. Prefer small, single-purpose tests.
- Silencing a failing test. Commenting out or skipping a failing test is worse than deleting it, because the suite looks green while the bug remains. Fix the code or fix the expectation instead of muting the test.
Best Practices
- Name each test for the behaviour it verifies, such as
testEmptyCartTotalsZero, so a failing name reads as a sentence describing what broke.
- Follow arrange-act-assert: set up the situation, perform one action, then assert the outcome, keeping each test focused on a single behaviour.
- Prefer
assertSameoverassertEqualsso that type regressions cannot pass unnoticed.
- Build fresh fixtures in
setUpand release resources intearDown, so every test runs in genuine isolation.
- Use data providers to run one assertion across many input rows, so each case reports as its own named test rather than hiding inside a loop.
- Test the failure paths -- expected exceptions and invalid input -- as thoroughly as the happy path.
- Keep tests deterministic by injecting clocks, seeds, and fakes instead of touching real time, randomness, or the network.
- Run the suite on every change, ideally in continuous integration, so a regression is caught the moment it lands rather than in production.
Practice Exercises
- Write a
Stacktest that asserts callingpopon an empty stack throwsRuntimeException, using the exception-checking pattern from this lesson.
- Add a
tearDownstep to the harness that counts how many tests ran, and print that total after the suite finishes; confirm the count matches the number oftestmethods.
- Convert the
testDiscountRoundsToNearestCentloop into a proper data-provider shape: a method that returns an array of[input, percent, expected]rows, and a runner that executes each row as a separately named test.
- Add a
removemethod toCart, then write a test that adds three different items, removes one, and asserts that both the subtotal and the count are correct afterwards.