Summary - Testing basics
Write a test suite for a calculator class with PHPUnit, assertions and mocks.
Summary - Testing basics
In this group you saw the six pillars of testing basics: PHPUnit runs unit tests, TestCase is the base of test classes, assertions like assertEquals/assertTrue check the result, the AAA pattern organises the test, mock/stub isolate dependencies, setUp/tearDown manage shared setup. The last step combines these ideas into a tiny test runner of our own: a small tool that checks assertions even without PHPUnit installed.
Our own test runner
To see the test logic without PHPUnit installed, we can write a tiny runner of our own. Functions like assertEquals check a condition and throw on failure. A runTest function calls the test, prints its name on success, and shows the error on failure. This helps you see inside PHPUnit; the real tool does much more: parallel runs, output capture, coverage measurement.
Exercise Write your own test runner
Write your own test runner. The assertEquals function compares two values and throws an Exception if they differ. The runTest function takes a callable test, prints its name with PASSED on success, and the error message on failure. Then call a test named "testAdd" with runTest that checks assertEquals(4, 2 + 2).
Show example solution
void { if ($expected !== $actual) throw new Exception("Expected $expected, got $actual"); }. Write function runTest(callable $test, string $name): void { try { $test(); echo "$name: PASSED\n"; } catch (Exception $e) { echo "$name: FAILED - " . $e->getMessage() . "\n"; } }. Then add runTest(function () { assertEquals(4, 2 + 2); }, "testAdd");
Example solution:
<?php
// Write the assertEquals and runTest functions
function assertEquals($expected, $actual): void {
if ($expected !== $actual) {
throw new Exception("Expected $expected, got $actual");
}
}
function runTest(callable $test, string $name): void {
try {
$test();
echo "$name: PASSED\n";
} catch (Exception $e) {
echo "$name: FAILED - " . $e->getMessage() . "\n";
}
}
// Call the testAdd test with runTest
runTest(function () {
assertEquals(4, 2 + 2);
}, "testAdd");
Test yourself
-
Match the six pillars
- TestCase
- Base class
- assertEquals
- Assertion
- AAA
- Test layout
- Mock
- Fake object
- setUp
- Setup
-
Complete the error handling line
<?php function assertEquals($expected, $actual): void { if ($expected !== $actual) { throw new Exception("Expected $expected, got $actual"); } } function runTest(callable $test, string $name): void { try { $test(); echo "$name: PASSED\n"; } catch (Exception $e) { echo "$name: FAILED - " . $e->____() . "\n"; } }Show answer
<?php function assertEquals($expected, $actual): void { if ($expected !== $actual) { throw new Exception("Expected $expected, got $actual"); } } function runTest(callable $test, string $name): void { try { $test(); echo "$name: PASSED\n"; } catch (Exception $e) { echo "$name: FAILED - " . $e->getMessage() . "\n"; } }