Test PHP code with PHPUnit
8 steps · about 2 h 5 min · Intermediate
- Install PHPUnit as a Composer dev dependency (doc, PHPUnit, 10 min)
Gets a project-local PHPUnit with the right PHP extensions checked.
- Write a first test case class (doc, PHPUnit, 20 min)
Covers test naming, dependencies, data providers and expected exceptions.
- Choose the right assertion for each check (reference, PHPUnit, 15 min)
The full list of assertions with clear failure output.
- Share setup with setUp and tearDown fixtures (doc, PHPUnit, 10 min)
Keeps each test independent without repeating setup code.
- Configure tests with PHP attributes (reference, PHPUnit, 15 min)
Attributes like DataProvider and CoversClass replace old docblock annotations.
- Isolate a class with stubs and mocks (doc, PHPUnit, 25 min)
Shows how to fake collaborators and verify calls.
- Set up phpunit.xml for suites and source paths (doc, PHPUnit, 15 min)
One config file defines test suites, bootstrap and source for coverage.
- Measure which lines your tests cover (doc, PHPUnit, 15 min)
Coverage reports show untested branches worth new tests.