Test PHP code with PHPUnit

8 steps · about 2 h 5 min · Intermediate

  1. Install PHPUnit as a Composer dev dependency (doc, PHPUnit, 10 min)

    Gets a project-local PHPUnit with the right PHP extensions checked.

  2. Write a first test case class (doc, PHPUnit, 20 min)

    Covers test naming, dependencies, data providers and expected exceptions.

  3. Choose the right assertion for each check (reference, PHPUnit, 15 min)

    The full list of assertions with clear failure output.

  4. Share setup with setUp and tearDown fixtures (doc, PHPUnit, 10 min)

    Keeps each test independent without repeating setup code.

  5. Configure tests with PHP attributes (reference, PHPUnit, 15 min)

    Attributes like DataProvider and CoversClass replace old docblock annotations.

  6. Isolate a class with stubs and mocks (doc, PHPUnit, 25 min)

    Shows how to fake collaborators and verify calls.

  7. Set up phpunit.xml for suites and source paths (doc, PHPUnit, 15 min)

    One config file defines test suites, bootstrap and source for coverage.

  8. Measure which lines your tests cover (doc, PHPUnit, 15 min)

    Coverage reports show untested branches worth new tests.