php · level 3 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Pence and pounds, tested. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?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";
}
}
assert_same("adds pence", 30, 10 + 20);
assert_same("adds pounds", 0.3, 0.1 + 0.2);
your turn
Your turn. Test the slug maker.
Type a title in the first blank, spaces and capitals allowed. In the second, type the slug you expect. PASS means you and the code agree.
fix it
Both tests fail. Find the bug they point at.
- Read the FAIL lines. Each answer is exactly one more than expected. Where could an extra 1 come from?
- The tests are right, so the bug is in
halfPriceitself, on line 10. - Remove
+ 1from line 10, then run the tests again.
nailed it
you wrote tests that check themselves. :D
- An assertion compares the expected value with the real one.
- Each test case checks one behaviour: arrange, act, assert.
var_exportshows values exactly, so failures are clear.
new words in your collection
- assertion
- test case
- arrange, act, assert
This lesson isn’t saved. A free account remembers every lesson you finish.