Unit Testing

Let’s learn how to write unit tests for our application.

Unit tests check single code units (like functions or classes) in isolation. Usually, they are small, fast, and numerous. It’s worth covering every piece of logic in the application with unit tests. If something breaks, a failed unit test will show what exactly is broken.

How to write unit tests

Initial setup

Before running tests locally or in the CI pipeline, we have to install the testing framework. The most common one in PHP is PHPUnit. Please refer to the “Getting Started” guide in the PHPUnit documentation to learn how to install it. It’s not the only framework, but the code examples in this lesson use PHPUnit.

Writing a test

Every test is composed of these three stages, often referred to as the Arrange-Act-Assert pattern:

  • Arrange sets the environment required by the unit of code we’re testing and creates the input data.
  • Act runs this unit of code.
  • Assert makes assertions on the action results.

In the Assert phase, we compare the result to the manually hard-coded, expected result—for example, we might expect that the output of the string reverse function for abcde should be edcba. Or, we can make assertions on output properties—for example, the output of the string reverse function should have the same length as the input. We shouldn’t calculate the expected result dynamically because if the test duplicates implementation logic, it also duplicates its bugs.


Let’s test our buggy word_count function again.

Get hands-on with 1200+ tech skills courses.