×

php · level 3 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An compares what you expected with what you got.

Big testing tools like PHPUnit are built on one tiny idea: the assertion. It compares an expected value with the real one and reports PASS or FAIL. Write your own assert_same in a few lines and you can test anything.

Each is a small function checking one behaviour, in three parts: . Set things up, do the one action, then check. var_export writes a value the way PHP code would, so a failure shows '0' and 0 differently.

<?php
function assert_same(string $name, mixed $expected, mixed $actual): void {
    if ($expected === $actual) {
        echo "PASS $name\n";
    } else {
        echo "FAIL $name: expected " . var_export($expected, true) . ", got " . var_export($actual, true) . "\n";
    }
}
function basketTotal(array $prices): int { return array_sum($prices); }
function test_total_adds_prices(): void {
    $prices = [120, 80];
    $total = basketTotal($prices);
    assert_same("total adds prices", 200, $total);
}
test_total_adds_prices();
assert_same("empty basket", "0", basketTotal([]));

mixed is the type that accepts any value at all, which suits a helper that compares anything.