What is PHPUnit?
Learn the PHPUnit testing framework and the goals of unit testing.
What is PHPUnit?
PHPUnit is the most popular test framework for PHP. It tests small pieces of code in isolation; these are called unit tests. It automatically finds methods that start with test and checks expected results with assertions like assertEquals. Install it with composer require phpunit/phpunit. Tests usually live in the tests directory and run with vendor/bin/phpunit. Bugs are caught early and refactoring becomes safer.
Test class structure
Every test class extends PHPUnit\Framework\TestCase. First import it with use PHPUnit\Framework\TestCase;, then write class CalculatorTest extends TestCase. Class names usually end with Test: CalculatorTest, UserTest. Test methods must start with test: public function testAdd(): void. PHPUnit finds these methods automatically and runs them in order.
Exercise Write your first test class
Make CalculatorTest extend TestCase. Write a testAdd method that checks $this->assertEquals(4, 2 + 2) verifies 2 plus 2 equals 4.
Show example solution
void { $this->assertEquals(4, 2 + 2); }.
Example solution:
<?php
// Here we define TestCase ourselves; in real code you use PHPUnit\Framework\TestCase
class TestCase {
protected function assertEquals($expected, $actual): void {
if ($expected !== $actual) {
throw new Exception("Expected $expected, got $actual");
}
}
}
class CalculatorTest extends TestCase {
public function testAdd(): void {
$this->assertEquals(4, 2 + 2);
}
}
// Run the test
$test = new CalculatorTest();
$test->testAdd();
echo "testAdd: PASSED\n";
Test yourself
-
What kind of tests does PHPUnit run?
- Only large system tests
- Unit tests
- Only browser tests
- Only database queries
Show answer
Unit tests — Correct. PHPUnit runs unit tests; each tests one small piece.
-
Extend TestCase
<?php use PHPUnit\Framework\TestCase; class CalculatorTest ____ TestCase { public function testAdd(): void { $this->assertEquals(4, 2 + 2); } }Show answer
<?php use PHPUnit\Framework\TestCase; class CalculatorTest extends TestCase { public function testAdd(): void { $this->assertEquals(4, 2 + 2); } } -
Match the concepts
- TestCase
- Base class
- testAdd
- Test method
- assertEquals
- Assertion
- tests/
- Test directory